Clearing cin input: is cin.ignore not a good way?

后端 未结 2 816
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 07:29

What\'s a better way to clear cin input? I thought cin.clear and cin.ignore was a good way?

Code:

 void clearI         


        
2条回答
  •  醉酒成梦
    2021-01-12 07:42

    Copy-pasting from the standard,

    basic_istream&
    ignore(streamsize n = 1, int_type
    delim = traits::eof());
    

    Effects: Behaves as an unformatted input function (as described in 27.6.1.3, paragraph 1). After constructing a sentry object, extracts characters and discards them. Characters are extracted until any of the following occurs:

    • if n != numeric_limits::max() (18.2.1), n characters are extracted
    • end-of-file occurs on the input sequence (in which case the function calls setstate(eofbit), which may throw ios_base::failure (27.4.4.3));
    • c == delim for the next available input character c (in which case c is extracted).

    You commented line with numeric_limits<>::max is superior, but it looks like you didn't want to use something you didn't completely understand, which is also good.

    The only thing someone could possibly want besides ignore is non-blocking behavior, i.e. don't wait for the user to press return if the terminal is in unbuffered mode. But that's just entirely unsupported by iostreams as far as I know.

提交回复
热议问题