+ 2
80.2 Practice - String, Input, Length, Status
You are making a program to manage user names. A valid username needs to be minimum 4, maximum 20 characters long. Create a program to take a string as input, check its length and output "Valid" if the name is valid, or "Invalid", if it is not. *You can check the length of the input string using the size() function and throw an exception, if it is not valid. My code as below. It got 3 out of 4 test correct. The incorrect test is hidden so I’m not sure what’s wrong.
3 Réponses
+ 3
It says that the minimum length is 4 characters and the maximum is 20, so in other words 4 and 20 are inclusive, you're using the incorrect comparison operators.
Capitalization of valid and invalid might play another role.
Also, when the instruction mentioned the use of the size() function it was referring to the member function of string. name.size() in this case.
size(name) works, it internally calls name.size() but be aware that it is a C++17 or C++20 feature ( I can't remember at the top of my head. ) Handy for templates.
I also recommend that you don't use throw/catch for simple error checking like this. The invalid output can go inside the else branch and you'll have cleaner code.
0
#include <iostream>
using namespace std;
int main() {
string name;
cin >> name;
try {
if(size(name)>4 && size(name)<20){
cout<<"valid";
}
else{
throw 0;
}
}
catch(int x)
{
cout<<"Invalid";
}
return 0;
}
0
Thanks Dennis. It works after I did minor change to >3 and <21 and to Valid.