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:
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;
}
defines
std::basic_ios
inoperator bool
:So if the standard IO stream is judged by
if (!cin)
in the form ofbool
,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 inif (!cin)
will be judged to be true. At this time,cin.clear()
can be called to reset the state of the stream, andcin.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: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.
cin
is the input stream, and!cin
is to determine whether the input stream is normal.