+ 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.

10th Jan 2022, 10:14 PM
Chin Eu
Chin Eu - avatar
3 odpowiedzi
+ 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.
10th Jan 2022, 11:42 PM
Dennis
Dennis - avatar
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; }
10th Jan 2022, 10:14 PM
Chin Eu
Chin Eu - avatar
0
Thanks Dennis. It works after I did minor change to >3 and <21 and to Valid.
11th Jan 2022, 8:38 AM
Chin Eu
Chin Eu - avatar