So i’m making a menu in a simple console app.
My code is pretty much: (LINKS TO ACTUAL CODE AT THE BOTTOM!)
int input;
bool LOOPING = true;
while(LOOPING)
{
cout << "Select an option:\n";
cout << "1 - option 1\n";
cout << "2 - option 2\n";
cout << "3 - option 3\n";
cout << "4 - option 4\n>";
cin >> input;
switch(input) {
case 1:
game();
break;
case 2:
game();
break;
case 3:
game();
break;
case 4:
game();
break;
default:
cout << "ERROR: invalid input!\nPlease enter in a number!\n\n";
break;
}
}
// rest of app...
My problem is, the program just goes into a constant loop of text! Why is this happening? Why does default: not stop that from happening and how do i stop this from occuring?
Thanks in advance!
EDIT: asked for real code.
http://pastie.org/2415852
http://pastie.org/2415854
http://pastie.org/2415855
Your code is looping infinitely because you never set
LOOPINGto false. In the real code you only set it to false when the user chooses to exit, which will never happen because the user is not able to enter input anymore after he inputs a non-number for the first time.The reason that it doesn’t keep asking you for input after you entered a character is that
>>does not consume invalid input. I.e. if>>is supposed to write into anint, but what the user enters is not a valid int, it will not write to the int, but it will also not remove the user input from the stream (instead it will simply setcin‘s error flag, which you should check).The input will stay in the stream until you write it somewhere else or discard it. Until you do that every subsequent attempt to read an
intwill fail because the invalid input is still in the stream.