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;
        }
    }
2
  • 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. Commented Dec 23, 2011 at 16:43
  • 1
    Translation: "Enter number of steps" Commented Dec 23, 2011 at 16:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.