How does cin.clear() clear the input buffer?

血红的双手。 提交于 2019-12-10 17:07:12

问题


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 get std::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 while stream.peek() yields a character class you don't like (e.g., while isdigit(stream.peek()) yields false)



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!