fifiman
fifiman

Reputation: 264

C++ while loop not working

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string option;
    cout << "Would like water, beer, or rum?--> ";
    cin >> option;
    while( option != "water" || option != "beer" || option != "rum" )
        {
        cout << "You did not choose a valid option. Try again.\n";
        cout << "Would you like water, beer, or rum?-->";
        cin >> option;
        }
}

Why doesn't this code ever exit the loop even though the user enters the right option?

Upvotes: 2

Views: 3713

Answers (6)

David G
David G

Reputation: 96810

Your ||s should be &&s because a option can only have one value.

while (option != "water" && option != "beer" && option != "rum")
{
   // ...
}

Upvotes: 2

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

You can use a container to store the valid options and check to see whether the selection is in the container:

set<string> validOptions = { "water", "beer", "rum"};

while(validOptions.count(option) == 0) {
    // .. etc
}

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

Almost always != || sequences are wrong and && should be used. If one comparison fails the others are true, hence the entire condition is always true. If you are not unequal to one you are certainly unequal to others.

With experience you'll itch seeing such a construct.

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 372794

This statement is always true:

option != "water" || option != "beer" || option != "rum"

If option is "water," then it's not "beer," so the statement is true. If option is "beer," it's not "water," so the statement is true (assuming you have a good beer, of course.)

I think you meant to write

option != "water" && option != "beer" && option != "rum"

That way, as soon as option takes on any of these values, the loop will exit.

Hope this helps!

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258608

Read your condition out loud - "run the loop while option is not "water" or option is not "beer" or...".

When should it stop?

Upvotes: 11

Eric Finn
Eric Finn

Reputation: 9005

You are using the wrong logical operator. You want all of your conditions to be true (option not equal to water, not equal to beer, and not equal to rum), so you should be using and (&&). Or (||) means that the expression is true if any of the conditions are true, and since the values are mutually exclusive, that will always be the case, hence your infinite loop.

Upvotes: 3

Related Questions