Reputation: 10669
Below is the code for a simple menu in C++. For some reason, if you give it garbage input it will react properly ("Please try your selection again"). However it will then go through the loop one more time giving the error message again, and then finally go back to functioning like normal.
EDIT
The input variable is a char. If the garbage input is only one character long, then the loop works as it is supposed to. If there are any additional characters that will result in the loop being executed more than once before the user is allowed to input anything again.
char input = 0;
while (input != 4)
{
cout << "1. Circle";
cout << "\n2. Rectangle";
cout << "\n3. Triangle";
cout << "\n4. Quit";
cout << "\nChoose a shape: ";
cin >> input;
switch(input)
{
case '1':
circleFunctions();
break;
case '2':
rectangleFunctions();
break;
case '3':
triangleFunctions();
break;
case '4':
exit(4);
default:
cout << "\nPlease try your selection again...\n";
input = NULL;
cin.ignore();
break;
}
cin.ignore();
cout << "\n";
}
Upvotes: 0
Views: 259
Reputation: 10669
Found the answer. Adding the following parameters to cin.ignore made it work:
cin.ignore(20, '\n');
Upvotes: 1
Reputation: 541
You simply need to clear the input buffer when the default case is encountered,
std::cin.clear();
After that ignore everything in the input stream,
std::cin.ignore(INT_MAX);
That should put the cin buffer in a good state and the extraction operator (>>) should work properly.
Upvotes: 0