Search code examples
c++conditional-statementscomparison

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

  • You need to use && instead of || because using || the condition in the while is always true. When you write “r”, for example, the condition userinput != r is false but the rest are true, with && all the expressions turn to false and the while ends.