lPing7 lPing7 - 1 year ago 101
C++ Question

Infinite Loop when a character is entered

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

int ch;

cout<<"Enter: \n";
case 1:
case 2:
}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'.

Answer Source

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.

You complete code could look something like

int n;
    if (!std::cin >> n)
        std::cout << "Only numbers accepted. Please try again.\n";
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // Skip bad input
        std::cin.clear();  // Clear error flags

    // switch ...
} while (...);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download