Search code examples
c++error-handlingerror-checking

Why do I get an infinite loop when I press a letter? How do I change for error checking?


Why do I get an infinite loop when I press a letter? How do I prevent my code from going into an infinite loop when error checking?

#include <iostream>
using namespace std;

int main()
{
    int number;
    cout << "Enter a number in the range 1-100: ";
    cin >> number;

    while (number > 1 || number < 100)
    {
        cout << "ERROR: Enter a value in the range 1-100: ";
        cin >> number;

    }
    return 0;
}

Solution

  • Because std::cin is type safe, it knows that a letter is not a valid input for "int number". It raises an error flag in std::cin and any subsequent operation will fail and return immediately.

    You'll need to check the error state and clear any error flag(s) before you can proceed.

    See existing post Why do I get an infinite loop if I enter a letter rather than a number?