What\'s a better way to clear cin input? I thought cin.clear and cin.ignore was a good way?
Code:
void clearI
Copy-pasting from the standard,
basic_istream<charT,traits>& 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<streamsize>::max()(18.2.1),ncharacters are extracted- end-of-file occurs on the input sequence (in which case the function calls
setstate(eofbit), which may throwios_base::failure(27.4.4.3));c == delimfor the next available input characterc(in which casecis 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.
Your teacher’s reply are a bit unclear (at least to me).
Concerning ignore, your teacher is wrong in principle: ignore is the standard idiom of how to clear a stream (as shown by Potatocorn, this is even mentioned in the standard).
However, it’s important to notice that cin.ignore(1000) is indeed a bad way of doing this: this just presumes that there won’t be more than 1000 characters in the buffer. Never use such a magic number in ignore.
Instead, either use
cin.rdbuf()->in_avail() (i.e. the available number of chars in the read buffer)1), or usenumeric_limits<streamsize>::max().1) Unfortunately, in_avail is broken on some recent VC (?) compilers so this method isn’t very portable.