c++if-statementwhile-looplogical-orlogical-and

While loop not breaking?? C++


I'm trying to construct a simple dice game in C++. I do not understand why it's not breaking out of the while loop.

You are supposed to ONLY be able to bet 100, 300, or 500€.

Even if I enter my bet "100-300-500" which is supposed to be correct. It still loops and says it's an invalid bet. Why doesn't it progress to the if statement when I have if ((bet1 == 100) || (bet1 ==300) || (bet1==500))

I've tried putting the if statement before the while loop and all sorts of things. I can't get it to work.

cout << "Please place a bet. 100, 300, 500kr" << endl;
cin >> bet1;

while ((bet1 <= 99) || (bet1 >= 101) || (bet1 <= 299) || (bet1 >= 301) || (bet1 <= 499) || (bet1 >= 501)) {
    cout << "Please place a valid bet" << endl;
    cin >> bet1;
}
if ((bet1 == 100) || (bet1 ==300) || (bet1==500)) {
    cout << "You have deposited " << " " << bet1 << "" << "And you now have: "<< saldo - bet1 << " " << "Remaining on your account." << endl;
}

Solution

  • This loop

    while ((bet1 <= 99) || (bet1 >= 101) || (bet1 <= 299) || (bet1 >= 301) || (bet1 <= 499) || (bet1 >= 501)) {
        cout << "Please place a valid bet" << endl;
        cin >> bet1;
    }
    

    is an infinite loop for any valid entered value 100, 300 or 500.

    For example if the user will enter 100 then at least this condition (bet1 <= 299) evaluates to true. If the user will enter 300 then at least this condition (bet1 >= 101) evaluates to true. If the user will enter 500 then at least again this condition (bet1 >= 101) evaluates to true.

    You should rewrite the while loop for example like

    while ( bet1 != 100 && bet1 != 300 && bet1 != 500 )  {
        cout << "Please place a valid bet" << endl;
        cin >> bet1;
    }
    

    Using your approach to writing the loop the condition can look like

    while ( ( bet1 <= 99 ) || ( bet1 >= 101 && bet1 <= 299 ) || (bet1 >= 301 && bet1 <= 499 ) || ( bet1 >= 501 ) ) {
        cout << "Please place a valid bet" << endl;
        cin >> bet1;
    }