Letters stored as integers

33 views Asked by At
#include <iostream> 
#include <string>

using namespace std;

int main()
{
    cout << "Please enter an integer between 1 and 5" << endl;
    int x;                                                      //Selection of menu prompt
    cin >> x;
    while (x < 1 || x > 5)                                      //Tossing out garbage input
    {
        cout << "Invalid selection, please make another." << endl;
        cin >> x;
    }
    return 0;
}

When this is run, entering "a" for example, enters the while loop, but does not wait for user input at "cin >> x;" and instead loops infinitely through. Can someone explain to me why this happens and how I might fix the issue? I can only imagine it is something to do with the keyboard buffer.

2

There are 2 answers

0
Drew Noakes On BEST ANSWER

In this code, it's possible for cin to enter an error state. If the user does not enter an integer, it will fail.

That is, if the user enters a, then cin >> x does not set x, and future calls to cin >> x do not block. You see an endless loop.

You can check for this failure status and clear it. before continuing using code similar to:

if (cin.fail())
{
    cin.clear();
    cin.ignore();
    cerr << "Invalid selection, please make another." << endl;
}
0
SMA On

You really should use cin.clear() and cin.ignore() after accepting the input.

cin.clear() clears the error flag on cin, and then cin.ignore(5000, '\n') skips to the next newline. It will skip up to 5000 characters, so the code is assuming the user will not put in a very long.