0

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
Rhexis
  • 2,414
  • 4
  • 28
  • 40

1 Answers1

7

Your code is looping infinitely because you never set LOOPING to 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 an int, 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 set cin'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 int will fail because the invalid input is still in the stream.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • when you enter numbers in though and never characters you can exit. i want to stop characters (IF ENTERED BY MISTAKE) to not cause it to never end in a crazy loop – Rhexis Aug 23 '11 at 09:15
  • 2
    And to clear the `cin` buffer (something you'll have to do in the `default`: http://stackoverflow.com/questions/257091/how-do-i-flush-the-cin-buffer ) – xanatos Aug 23 '11 at 09:15
  • 2
    @Flyphe: Yes, if you enter numbers, the number is stored in the int and then removed from the stream. So the next time you try to read from the stream, the stream will be empty and the user will be asked for input. But when you enter a character, as I said, the input will not be removed from the stream (because it couldn't be written to the int). So the next time you try to read from the stream the input is still there and `>>` will try to parse it again and again it will fail. ... – sepp2k Aug 23 '11 at 09:29
  • 1
    ... As I explained: To get it to ask for input again, you'll need to clear the invalid input from the stream (for example by clearing the stream, which xanatos showed you how). – sepp2k Aug 23 '11 at 09:29