Resetting the State of a Stream

后端 未结 1 1628
夕颜
夕颜 2020-12-03 19:03

I have a question which is slightly similar to this question on stackoverflow std::cin.clear() fails to restore input stream in a good state, but the answer provided there d

相关标签:
1条回答
  • 2020-12-03 19:25

    The code here

    std::cin.clear(std::istream::failbit);
    

    doesn't actually clear the failbit, it replaces the current state of the stream with failbit.

    To clear all the bits, just call clear().


    The description in the standard is a bit convoluted, stated as the result of other functions

    void clear(iostate state = goodbit);

    Postcondition: If rdbuf()!=0 then state == rdstate(); otherwise rdstate()==(state | ios_base::badbit).

    Which basically means that the next call to rdstate() will return the value passed to clear(). Except when there are some other problems, in which case you might get a badbit as well.

    Also, goodbit actually isn't a bit at all, but has the value zero to clear out all the other bits.

    To clear just the one specific bit, you can use this call

    cin.clear(cin.rdstate() & ~ios::failbit);
    

    However, if you clear one flag and others remain, you still cannot read from the stream. So this use is rather limited.

    0 讨论(0)
提交回复
热议问题