Search code examples
c++loopswhile-loopinfinite

Stuck in Infinite While Loop, what to do


This does not accept any answer:

cout << "Restart yes or no: ";
cin >> retry;
while (retry != "yes" or retry != "no"){
    cout << "Restart yes or no: ";
    cin >> retry;
    system("cls");
}

If anybody can provide an alternative/fix it would be greatly appreciated.


Solution

  • Your code has retry != yes or retry != no. This condition is a tautology, and so will always evaluate to true.

    Edit your code to:

    cout << "Restart yes or no: ";
    cin >> retry;
    while (retry != "no"){
        cout << "Restart yes or no: ";
        cin >> retry;
        system("cls");
    }
    

    If you meant to loop until a yes or no is received, then the while loop should run until the string inputted is not equal to either. You meant to use a logical AND in place of the OR. The code should read:

    while (retry != "yes" && retry != "no"){