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?