伊谢尔伦2017-04-17 14:59:46
defines std::basic_ios
in operator bool
:
explicit operator bool() const; //C++11
So if the standard IO stream is judged by if (!cin)
in the form of bool
, operator bool
will be called, and the returned result will be used as the judgment condition of if.
So when an error occurs in the cin
input stream, the condition in if (!cin)
will be judged to be true. At this time, cin.clear()
can be called to reset the state of the stream, and cin.ignore()
can be called to clear the input buffer. to eliminate the impact of the last input on the next input. A common approach is:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Usually, the first parameter is set large enough so that only the second parameter 'n' actually takes effect, so that the input characters before the carriage return can be erased from the input buffer stream. Then try to read the next input.
if (!cin)
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
怪我咯2017-04-17 14:59:46
cin
is the input stream, and !cin
is to determine whether the input stream is normal.