问题
From what I have read, cin.clear()
resets the flags, but how does this clear the input buffer?
回答1:
cin.clear()
has no effect on the input buffer. As you correctly read, it resets the iostate
flags (technically, replaces their current value with std::ios_base::goodbit
)
回答2:
std::ios::clear()
only resets the error flags, if possible. If there is, e.g., no stream buffer (i.e., stream.rdbuf()
yield nullptr
) the std::ios_base::badbit
still stays set. That is the only affect. In particular, std::ios_base::clear()
does not remove any characters from an input buffer.
If you need to remove character from the input buffer, you'll need to do it explicitly. For example you can use
stream.ignore();
to unconditionally remove the next character (if any; if there is none, the stream will getstd::ios_base::eofbit
set).stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
to remove all character up to and including the first'\n'
character encountered.- you might want to
ignore()
characters whilestream.peek()
yields a character class you don't like (e.g., whileisdigit(stream.peek())
yieldsfalse
)
回答3:
cin.clear() doesn't clear the buffer, it only overwrites the current values of the flag. For more details you can visit this link--> http://www.cplusplus.com/reference/ios/ios/clear/
And You can find a good example in this link-->http://web.eecs.utk.edu/~plank/plank/classes/cs102/Cin-Notes/
回答4:
Indeed cin.clear()
has no effect on the input buffer it only sets a new value for the stream's internal error state flags.
If you want to clear the characters that "broke" your stream, you must use cin.ignore()
(e.g., cin.ignore(10000,'\n');
)
You can find a nice explanation with intuitive examples here: http://www.arachnoid.com/cpptutor/student1.html
来源:https://stackoverflow.com/questions/20832289/how-does-cin-clear-clear-the-input-buffer