While loop not executing condition correctly

Hi all,

I've written the following code but cannot understand why the loop ignores the condition. When the program runs and numbers above 5 and below 0 are entered(which makes the while condition true as far as I can understand) the program executes the cout statement outside the while statement instead of the while statement. I hope this makes some sort of sense. Not sure if my variable is initialised correctly.

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int beverage;
//Displaying the different choices of beverages
cout << "Please enter the choice of drink";
cout << " (a number from 1 to 4 or 0 to quit)" << endl;
cout << "Hot beverage Menu" << endl << endl;
cout << "1: Coffee " << endl;
cout << "2: Tea " << endl;
cout << "3: Hot Chocolate " << endl;
cout << "4: Cappuccino " << endl;
cout << "0: QUIT " << endl << endl;

cin >> beverage;
beverage != 0;

while (beverage < 1 && beverage > 5)
{
cout << "Invalid choice - Please re-enter ";
cin >> beverage;
}

cout << "You have selected option number " << beverage;

return 0;
}
while (beverage < 1 || beverage > 5)
If you have the logical AND &&, both of the conditions have to be true, which will never be the case.

while (beverage < 1 && beverage > 5)

Try changing to the logical OR.

while (beverage < 1 || beverage > 5)
1
2
3
4
5
6
7
while (beverage < 1 || beverage > 5)
{
    if(beverage==0)break;
    else
    cout << "Invalid choice - Please re-enter ";
    cin >> beverage;
}
beverage > 5

Did you mean to change the quit option to be 5 instead of 0, since you're checking for values greater than 5, not 4?
Well it should be
while (beverage < 1 || beverage > 4)
Thanks for your help. Much appreciated.
Topic archived. No new replies allowed.