'Infinite Loop when a character is entered [duplicate]

I am trying to restrict the user to enter only '1' or '2'.

int ch;

do
{
    cout<<"Enter: \n";
    cin>>ch;
    switch(ch)
    {
    case 1:
        cout<<"1";
        break;
    case 2:
        cout<<"2";
        break;
    default:
        cout<<"Retry\n";
    }
}while(ch != 1 && ch != 2);

When I enter any number other than 1 or 2, the program runs fine by asking user to retry, however when I enter a character, the program enters into an infinite loop of 'Retry' and 'Enter'.



Solution 1:[1]

That's because when you enter a non-digit character then the input operator can't parse that as an integer, and it leaves the character in the buffer. So next iteration of the loop it reads the exact same character again. And again and again and so on.

The simplest way to overcome this problem is to simply ask the stream to ignore the rest of the line:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input

There are other ways as well, like reading the whole line into a string, put that string into an input string stream, and read the integer from that stream instead. A little more work though. This way does mean you don't have to check for input failure on std::cin though which you must do with the above method.

Your complete code could look something like

int n;
do
{
    if (!std::cin >> n)
    {
        std::cout << "Only numbers accepted. Please try again.\n";

        // Skip bad input
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        std::cin.clear();  // Clear error flags
    }

    // switch ...
} while (...);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1