Yeo Jin Yeo Jin - 4 months ago 7
C++ Question

While loop in c++ cannot exit

I have this code, its just a part from another bigger code. This may seem like a very simple mistake, but I still cannot figure out what it is. My problem is that the value of 'house1' cannot exit the while loop and move on to switch statement. for example, if I entered house1 = 0, the program will print "Invalid value, please enter again" but if I entered house1 = 1 after I enter the invalid value, it will also print "invalid value, please enter again". Does anyone have any idea what was my mistake?

cin >> house1 ;
while ((0 <= house1) || (house1 >= 6))
{
cout << "Invalid value! please enter again:";
cin >> house1;
}
switch (house1)
{
case '1':
h1_p1 = h1_p1 - 5;
h2_p1 = h2_p1 + 1;
h3_p1 = h3_p1 + 1;
h4_p1 = h4_p1 + 1;
h5_p1 = h5_p1 + 1;
house_p1 = house_p1 + 1;
break;
case '2':
h2_p1 = h2_p1 - 5;
h3_p1 = h3_p1 + 1;
h4_p1 = h4_p1 + 1;
h5_p1 = h5_p1 + 1;
house_p1 = house_p1 + 2;
break;

Answer

If you meant the valid value should be from 1 to 5, the condition should be

while ((house1 <= 0) || (house1 >= 6))
{
    cout << "Invalid value! please enter again:";
    cin >> house1;
}

BTW: You're not checking invalid input (the failbit of cin) for house1.