简体   繁体   中英

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

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.

Both do different things. sync discards characters already read ahead, no matter how many there are, or what they are. On the other hand, ignore discards characters until a certain character is encountered, no matter whether those characters have already been read, or whether there are more characters already read ahead. For example, imagine that cin has a 40 byte buffer, but your line had 80 bytes. Then most likely the first 40 bytes had been read to cin 's buffer. After you've interpreted the beginning of those, by calling sync you discard the rest of those 40 characters you already have read , but not the other 40 characters in the line. On the other hand, your input might come from a pipe where no line buffering is typically done. In that case, you may discard not only the current line, but also parts of the next line which have been read ahead. OTOH with ignore you always know for sure that you'll always read up to the next \n (assuming the maximal number of characters to ignore is high enough to encounter it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM