Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

c++ - The difference between cin.ignore and cin.sync

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, ' ') 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(),'
'); //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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...