0

I'm trying to take an integer from the user. I'm using cin.ignore to make sure that the input is an int. However, when it is not an int, it causes the program to enter an infinite loop.

    int steps = 0;
    while (steps<2 || steps>100)
    {
        char tmp[1000];
        cout << "Zadejte pocet cyklu: ";


        cin >> steps;
        cin.ignore(numeric_limits<int>::max(), '\n');
        if (!cin || cin.gcount() != 1)
        {
            cin.getline(tmp,1000);
            steps = 0;
        }
    }
patokun
  • 113
  • 1
  • 1
  • 7
  • You don't seem to increase/decrease your steps variable anywhere which could lead to a infinite loop if you input something larger than 100 or smaller than 2. – lfxgroove Dec 23 '11 at 16:43
  • 1
    Translation: "Enter number of steps" – Phonon Dec 23 '11 at 16:44

1 Answers1

2

If the input stream doesn't contain an integer when you do cin >> steps, the stream enters an error state, which must be explicitly cleared (cin.clear()). Until then, the error state remains, and all further attempts to input will be treated as no-ops.

James Kanze
  • 150,581
  • 18
  • 184
  • 329