Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between cin.ignore and cin.sync

Tags:

c++

iostream

What is the difference between cin.ignore and cin.sync ?

like image 233
5fox Avatar asked May 14 '12 14:05

5fox


People also ask

What does Cin ignore mean?

The cin. ignore() function is used which is used to ignore or clear one or more characters from the input buffer. To get the idea about ignore() is working, we have to see one problem, and its solution is found using the ignore() function.

What is the difference between Cin clear and CIN ignore?

The cin. clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin. ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure).

What does Cin clear mean?

In C++ the cin is used to take input from user. Sometimes for some reasons some error flags are set. In that time the cin does not take any input. Sometimes it takes some other characters. So if we clear the cin, then the error flags are reset.

How do you reset a cin buffer?

In order to clear the input buffer after the user has entered too many characters, you will need to clear the status flags of the input stream and then ignore all cahracters up to the newline. This can be done like so: cin. clear(); cin.


1 Answers

cin.ignore discards characters, up to the number specified, or until the delimiter is reached (if included). If you call it with no arguments, it discards one character from the input buffer.

For example, cin.ignore (80, '\n') would ignore either 80 characters, or as many as it finds until it hits a newline.

cin.sync discards all unread characters from the input buffer. However, it is not guaranteed to do so in each implementation. Therefore, ignore is a better choice if you want consistency.

cin.sync() would just clear out what's left. The only use I can think of for sync() that can't be done with ignore is a replacement for system ("PAUSE");:

cin.sync(); //discard unread characters (0 if none)
cin.get(); //wait for input

With cin.ignore() and cin.get(), this could be a bit of a mixture:

cin.ignore (std::numeric_limits<std::streamsize>::max(),'\n'); //wait for newline
//cin.get()

If there was a newline left over, just putting ignore will seem to skip it. However, putting both will wait for two inputs if there is no newline. Discarding anything that's not read solves that problem, but again, isn't consistent.

like image 84
chris Avatar answered Oct 08 '22 22:10

chris