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

From what I read, cin.clear()flushes the flags, but how does it clear the input buffer?

+4
source share
4 answers

cin.clear()does not affect the input buffer. When you read correctly, it resets the flags iostate(technically, replaces their current value with std::ios_base::goodbit)

+3
source

std::ios::clear()only clears error flags if possible. If not, for example, there is no stream buffer (i.e. stream.rdbuf()yield nullptr), then the parameter std::ios_base::badbitremains set. This is the only affect. In particular, it std::ios_base::clear()does not remove characters from the input buffer.

, . ,

  • stream.ignore();, ( , , std::ios_base::eofbit).
  • stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');, '\n'.
  • ignore() , stream.peek() , (, isdigit(stream.peek()) false)
+2

Really cin.clear()does not affect the input buffer, it sets only a new value for the status flags of the internal error of the stream.

If you want to clear the characters that "broke" your stream, you should 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

+1
source

All Articles