Reputation: 143
I am starting to learn the C++ syntax and I am attempting to validate user input in a program I am writing. Here is what i try to do:
string genderC;
cout << "Enter 'm' for male and 'f' for female:" << endl;
cin >> genderC;
while( !(cin >> genderC) || genderC != 'f'|| genderC != 'm') {
cout << "Bad input\nEnter 'm' for male and 'f' for female:" << endl;
cin.clear();
}
//...
it gives me the following error:
invalid operands to binary expression ('string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') and 'int')
Any help would be appreciated. Thank you.
Upvotes: 1
Views: 303
Reputation: 1004
The genderC
variable is of type "string" and you are comparing it with 'f' and 'm' which are of type "char" due to the single quotes.
Your problem should be fixed if you rewrite your while loop like this:
while( !(cin >> genderC) || genderC != "f" || genderC != "m") {
Due to the double quotes, "f" and "m" are of type "char*" which can be compared with "string".
Note that the compiler is referring to those two literal "char" type as "int" because char is, in fact, an 8-bit integer.
Upvotes: 0
Reputation: 6363
You're comparing a string to a char. char is an integer type which is why you get the error message saying that you can't compare a string to an int.
'f'
and 'm'
are of type char
while genderC
has type std::string
.
So you have two options:
"f"
and "m"
(which are strings) insteadUpvotes: 1
Reputation: 53958
You have to change this
genderC != 'f'|| genderC != 'm'
to this:
genderC != "f" || genderC != "m"
The genderC
is a string
and a string
is a sequence of characters between two "
. If genderC
was a char
, you wouldn't had any problem.
Upvotes: 1