0

I discovered some very peculiar behaviour. I'm new to C++ so I found this odd and was unable to explain it after reading the docs on cin.ignore.

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    cin.ignore(10000, '\n');
    return 0;
}

The code above accepts input. If you add int test; cin>>test; right above cin.ignore, it will not accept input.

user2316667
  • 5,444
  • 13
  • 49
  • 71

1 Answers1

2

When you add input of an integer a newline (at least) is left in the input buffer, and then read by the ignore.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Not too sure what you mean... would you elaborate? – user2316667 Dec 07 '13 at 04:37
  • Let's say the user types "3.14" (without the quotes), and presses return. The input buffer then contains "3.14\n" (in C++ notation). Reading a `float` consumes the "3.14" and leaves the "\n". The `ignore` call then consumes the "\n". – Cheers and hth. - Alf Dec 07 '13 at 04:42
  • 1
    That doesn't explain why the code above pauses and waits for the user to type in input... I expected it to just 'consume' an empty buffer and move on. – user2316667 Dec 07 '13 at 04:45
  • 2
    The input buffer often becomes empty during ordinary input operations, and what happens then (when further input is attempted by the program) is just that a new line is fetched from the input source. `ignore` reads until the specified number of characters or until the specified terminator, whichever comes first. Just read [the documentation](http://en.cppreference.com/w/cpp/io/basic_istream/ignore). – Cheers and hth. - Alf Dec 07 '13 at 04:57