I have an "if" that looks like this, which is meant to detect whether the user has entered anything other than m/M/f/F:
if (sex != 'm' || sex != 'M' || sex != 'f' || sex != 'F')
If I enter something other than m/M/f/F the program is supposed to give an error message, as depicted in the following piece of code. Otherwise, it will continue onwards:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
char sex;
cout << "What is your gender? (M or F) ";
cin >> sex;
if (sex != 'm' || sex != 'M' || sex != 'f' || sex != 'F')
{
cout << "Please enter M or F" << endl;
return 0;
}
else
The problem right now is that I keep getting the error message even if
I enter one of m, M, f or F at the moment. what I am doing wrong?
This is a pretty simple problem I'm sure you can solve it yourself, choose a value for sex, let's say its 'm', and then evaluate the result of your if statement in your head. Remember that you're using the || operator, OR, so if any of those conditions is true, the result of the whole if statement is true and it will print your error message.
I know I wrote it wrong; I tried writing it as this:
if (sex != 'm' || 'M' || 'f' || 'F')
But that didn't work either - I can't figure out how to write the code as such that if sex does not equal any of those values the program will output the error code.
This is wrong, you had it right the first time. Note that the above code does not mean "if sex does not equal m or M or f or F". It means "if sex does not equal m returns true or if M returns true or if f returns true or if F returns true"...
As for your problem, your code says that your error message should be printed as long as either of those expressions are returned true.