Search code examples
c++windowsistream

Why would I even use istream::ignore when checking for valid input?


The C++ FAQ over at parashift uses something similar to the following:

while (cout << "Enter an integer: " && !(cin >> foo))
{
    cin.clear();

    //feel free to replace this with just (80, '\n') for my point
    cin.ignore (numeric_limits<streamsize>::max(), '\n');
}

The cin.ignore (...), however, seems unnecessary. Why can't I just use cin.sync()? It's shorter and does not require a length. It's also more versatile as it will work the same way whether or not there are any characters in the input buffer in the first place. I've tested this once in the same loop as I used with ignore and it worked the same way. Yet it seems every example involving this type of input validation uses ignore instead of sync.

What (if any) was the reasoning behind using ignore when there's a much simpler alternative?

If it matters:
Windows
GCC
MinGW


Solution

  • On an ifstream, the effect of sync() is implementation defined (per C++11, §27.9.1.5/19) -- there's no guarantee that it'll do what you want (and no real guarantee of what it'll do at all). In a typical case, it will be about equivalent to the ignore if and only if the stream is line buffered -- but if the stream is unbuffered, it probably won't do anything, and if the stream is fully buffered, it'll probably do bad things.