How to use multiple AND statement to check char

Viewed 37
while (weather != 'S' || 'R' || 'W') {

        cout << "Invalid input for weather" << endl;
        std::cout << "Please enter today's weather [S]unny, [R]ainy, [W]indy: " << endl;
        cin >> weather;
}

If weather is equal to S R or W I want it to continue on with the program but if its not S R or W then i want it to run the while statement. But even if the weather input is S R or W it runs the while statement anyway. Any advice?

Ive tried

while ((weather != 'S') || (weather != 'R') || (weather != 'W')) {

        cout << "Invalid input for weather" << endl;
        std::cout << "Please enter today's weather [S]unny, [R]ainy, [W]indy: " << endl;
        cin >> weather;
}

but that didn't work either. I even attempted

while (weather != 'S') {
     while (weather != 'R') { 
          while (weather != 'W')) {

        cout << "Invalid input for weather" << endl;
        std::cout << "Please enter today's weather [S]unny, [R]ainy, [W]indy: " << endl;
        cin >> weather;
          }
     }
}

but to nothing seems to work.

1 Answers

You want to execute the while loop if all the conditions are true, that means && not ||

while ((weather != 'S') && (weather != 'R') && (weather != 'W')) {

Try saying it out loud 'execute the loop if weather does not equal S and weather does not equal R and weather does not equal W'.

Another way to write the same condition is

while (!((weather == 'S') || (weather == 'R') || (weather == 'W'))) {

Try saying that one out loud 'execute the loop if it is not that case that weather equals S or weather equals R or weather equals W'.

It's very common for beginners to make logical errors where negation is involved. Probably you got the two possibilities above confused and came up with an expression that wasn't equal to either of them.

Related