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

前端 未结 3 1734
时光说笑
时光说笑 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 17:50

    iostreams is designed to detect errors and enter an error state. You get the same result from integer overflow as from entering a non-numeric string.

    Cast cin (or any stream) to bool or check cin.rdstate() to determine if an error has occurred.

    Call cin.clear() and cin.ignore() to flush out the error. It will pick up at the point of the characters that failed.

    As for the official documentation, the Standard unfortunately gets a bit inscrutable in the bowels of iostreams. See §27.6.1.2.1, 27.6.1.2.2, and 22.2.2.1.1/11 (no kidding):

    — The sequence of chars accumulated in stage 2 would have caused scanf to report an input failure. ios_base::failbit is assigned to err.

    The documentation for scanf is just as impenetrable, and I'll take it on faith that overflow is supposed to be an error.

    0 讨论(0)
  • 2021-01-18 17:55

    a starts out with an undefined value. It's not cin's fault. Try:

    if (cin >> a) {
      cout << a endl;
    }
    

    It will check whether the read into a succeeded before using a

    0 讨论(0)
  • 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 <iostream> 
    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; 
    }
    
    0 讨论(0)
提交回复
热议问题