Why does integer overflow cause errors with C++ iostreams?

前端 未结 3 1735
时光说笑
时光说笑 2021-01-18 17:27

Ok, so I have some problems with C++ iostreams that feels very odd, but it is probably defined behaviour, considering this happens with both MSVC++ and G++.

Say I ha

3条回答
  •  暖寄归人
    2021-01-18 18:12

    I'd think that cin is setting itself to an error state due to the invalid read.

    1st reply here explains it.

    http://www.dreamincode.net/forums/topic/93200-cin-checking-and-resetting-error-state/

    Just tried this code and it does seem to be setting to fail state

    #include  
    using namespace std; 
    
    int main() 
    { 
        int a; 
        cin >> a; 
        if(!cin)
        {
            cin.clear();
        }
        cout << a << endl; 
        cin >> a; 
        if(!cin)
        {
            cin.clear();
        }
        cout << a << endl; 
    
        return 0; 
    }
    

提交回复
热议问题