-2

I just recently picked up C++ and creating a simple RPG game for practice. But one problem I ran into was the switch statement being stuck in an infinite loop when it uses the default case.

My code essentially look like this:

while (cond)
{
    //Ask user for input 1-4
    cin >> choice;
    switch(choice - 1)
    {
         case 0:
               //Action
               break;
         case 1:
               //Action
               break;
         case 2:
               //Action
               break;
         case 3:
               //Action
               break;
         default:
              cout << "You entered an invalid command. Try again." << endl;
    }
}

Eventually cond will become false when the enemy HP is brought down to or below 0 through the //action in the cases.

But, when I enter a random key, it does go to the default case and ask for user input again but skips over the cin >> choice; and replays the default case again in an infinite loop.

How can I avoid that?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Stifpy
  • 19
  • 4
  • 2
    You never clear `cin`'s state after possibly invalid input. – πάντα ῥεῖ Jan 10 '19 at 23:12
  • 3
    Please provide a [mcve] – Robert Andrzejuk Jan 10 '19 at 23:12
  • see https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input – Wyck Jan 10 '19 at 23:24
  • https://stackoverflow.com/questions/5864540/infinite-loop-with-cin-when-typing-string-while-a-number-is-expected, https://stackoverflow.com/questions/27190382/avoiding-infinite-loop-when-a-char-is-enter-in-place-of-int – melpomene Jan 10 '19 at 23:24
  • 2
    This doesn’t address the question, but if the user is entering slurs from 1 to 4, I’d be inclined to use those values as the case labels, too. Subtracting 1 makes the code less clear. – Pete Becker Jan 10 '19 at 23:47

1 Answers1

1

You need to clear the input state and then ignore the junk that was invalid.

default:
    cout << "You entered an invalid command. Try again." << endl;
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

See also, this answer: Why would we call cin.clear() and cin.ignore() after reading input?

Wyck
  • 10,311
  • 6
  • 39
  • 60