Search code examples
while-loopintegerletters

Letters stored as integers


#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.


Solution

  • 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;
    }