'How do I get multiple conditions within one while loop?

I am using a while loop and I want to user to input r, R, p, or P. But when I add more than one condition like:

while ((userInput != "r") || (userInput != "p" || (userInput != "R") || (userInput!= "P")) {
    cout << "Please enter a valid option" << endl;
    cin >> userInput;
}

my program will forever be stuck in the loop. Where as if I input it like this:

while (userInput != "r") {
    cout << "Please enter a valid option" << endl;
    cin >> userInput;
}

Then my code will exit the for loop if user inputs "r" So why does the first block of code not work? I have no errors, which means it has to be a logical error but I do not understand. How can I get more thano ne condition in a for loop and make it work?



Solution 1:[1]

Why does the above condition not work?

The reason is because if you say x is not 3 or x is not 5, then if x is 3, then x is not 5, so the entire statement evaluates to true. Your different userInput != 'r' and userInput != 'p' are just like that situation with the x.

To show it simpler, I'll show a truth table for or. When the expression evaluates to true, your while loop would continue below those circumstances, where p and q are statements that may be true or false like userInput != 'r'.

||  -- or
 q\p|_T_|_F_|
 _T_|_T_|_T_|
 _F_|_T_|_F_|

Meaning that with an or clause, the only way it's false is if all parts are false.

An And clause appears to be what you want. It's truth table is:

&&  -- and
 q\p|_T_|_F_|
 _T_|_T_|_F_|
 _F_|_F_|_F_|

Meaning, that with an and clause, the only way for it to be true is if all clauses are true.

So if you want the response to be neither r nor p nor R nor P, etc, use && for and:

while ((userInput != "r") && (userInput != "p") && (userInput != "R") && (userInput!= "P")) {

And then the while loop will exit as soon as userInput does not match any of r, p, R or P. This is because as the program evaluates, it checks:

With the example of userInput as "g":

Does the userInput g equal r? No. So the first clause is True. Does the userInput g equal p? No. So the second clause is True. Does the userInput g equal R? No. So the third clause is True. Does the userInput g equal P? No. So the fourth clause is True. Since all four are true, then the whole statement is true, and the while loop continues.

With the example of userInput as "R":

Does the userInput g equal R? No. So the first clause is True. Does the userInput g equal R? No. So the second clause is True. Does the userInput g equal R? YES. So the third clause is False. Since a part of the statement is false, the whole and clause is false, so the while loop exits.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1