cin.ignore() seems to stop execution

When run, the following code seems to stop at cin.ignore(1000, '\n'); line, as "Enter some number" doesnt get printed.
Hitting carriage return causes the "Enter some number" line to display, and then the program works correctly in the following while loop iterations (meaning the "Enter some number: " gets displayed right away).

Why is that ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
    int a = 0;
    do
    {
        cin.clear();
        cin.ignore(1000, '\n');

        cout << "Enter some number: ";
        cin >> a;
        if(cin.fail())
        {
            cout << "Not a number!";
        }
    } while(cin.fail());

    cout << "Number given: " << a << "\n";

    return 0;
}


Last edited on
Since there is nothing in the buffer ignore() will wait until it actually finds the end of line character in the buffer.

You probably should rethink the logic of your loop, and place the clear() and ignore() inside the if statement.
When cin.ignore(1000, '\n'); is called the first time there is nothing in the input buffer so it waits until there is something in the buffer (when you press carriage return) and then clears it. To fix it you would have to move around that line and change the loop slightly. Or a simple way is to use a boolean variable that skips the the 'cin.ignore' the first time round but not any time thereafter.


EDIT: Didn't realise someone just posted exactly what I said so I'll add onto this post. Placing the 'cin.clear()' line in the 'if' statement would make the condition in the loop false even though it did fail so you would need to use a boolean variable or some alternative.
Last edited on
Topic archived. No new replies allowed.