c++ - if(! cin ) 是什么意思 有什么作用
大家讲道理
大家讲道理 2017-04-17 14:57:46
0
2
733

if(! cin ) 是什么意思,有什么作用,应该怎么用

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
伊谢尔伦

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;
}
刘奇

cin is the input stream, and !cin is to determine whether the input stream is normal.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template