search

Home  >  Q&A  >  body text

c++ - if(! cin ) 是什么意思 有什么作用

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

大家讲道理大家讲道理2807 days ago730

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦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;
    }

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:59:46

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

    reply
    0
  • Cancelreply