Hello im new with c++ and i try to make a game to learn some basic stuff.i have a problem with a loop.its supposed to repeat itself until the input is a number between 1 and 3. with other numbers it repeats itself normally but with a char the program enters an infinite loop.Please help ive been trying to fix this for over an hour!
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{int x;
do
{cout << "where do you want to go?"<<endl;
cout << "1=small cave"<< endl;
cout << "2=forest"<< endl;
cout << "3=large cave"<< endl;
cin >> x;
}while (x<1 or x>3);
}
If the user enters a char, then cin goes into an error state. You need to clear the error flags before taking further input.
Try,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{int x;
do
{
cout << "where do you want to go?"<<endl;
cout << "1=small cave"<< endl;
cout << "2=forest"<< endl;
cout << "3=large cave"<< endl;
if ( !(cin >> x) ) { // if there is an error while reading input
cin.clear(); // clear and reset the error flags
cin.ignore(256,'\n'); // ignore the entire line of bad input
}
}while (x<1 or x>3);
}