开发者

cin stream error

开发者 https://www.devze.com 2023-03-06 17:54 出处:网络
int main() { int i; if (cin >> i) { //ok } else { //error cin.开发者_如何学Gosetstate(std::ios_base::goodbit);
int main()
{
    int i;

    if (cin >> i)
    {
        //ok
    }
    else
    {
        //error
        cin.开发者_如何学Gosetstate(std::ios_base::goodbit);
    }
}

Why can't I set goodbit through setstate() to clear out the failbit instead of cin.clear()?


Because setstate combines the current state with whatever state you're passing it with a bitwise OR, ergo the fail bit doesn't get cleared (set to zero).

So assume:

Assume a very simple state mechanism:
00
^^
||
|\
| the fail bit
 \
   the ok bit

Doing setstate(okbit) when your state is 01 is just going to give you 11 (look ma, the fail bit is still set) so really all you're doing is screwing up the internal stream state. You should really avoid using setstate altogether.

Click for reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号