0

I had always assumed that if cin >> x fails, where x is a built-in type such as int, then x is left at its value prior to the input. However the following code produces different output depending on how cin fails:

#include <iostream>

using namespace std;

int main(){
    int x = 10, y = 10;

    cin >> x;
    cin >> y;

    cout << x << " " << y;
}

The value of y seems to vary depending on the type of failure (^Z representing EOF)

Input 20 ^Z outputs 20 0

Input 20 c output 20 0

Input 20[ENTER]^Z outputs 20 10

Input 20[ENTER] ^Z outputs 20 0

So it seems if there is a failure then int gets set to the value 0. However I can't make sense of the third case, where I enter 20, press enter and then Cntrl+Z, the value of y doesn't get changed at all in this circumstance.

How are values set when cin fails? Should I make any assumptions about their values? Also, when creating my own input operator for classes, should cin failures generally set the class object back to the pre-input value or to a default value instead (Class())?

SergeantPenguin
  • 843
  • 7
  • 16
  • A different compiler might behave differently. You can't count on the value when the operation fails. – R Sahu Dec 01 '15 at 22:19
  • @RSahu you can, since C++11 – M.M Dec 01 '15 at 22:21
  • @M.M, interesting. Good to know. – R Sahu Dec 01 '15 at 22:23
  • @RSahu While the duplicate did help, I still can't really understand the output. `20 ^Z` should be outputting `20 10` if `skipws` is turned on, which it isn't. If I try the input from a file (and swap `cin` to an `ifstream` object) it works as intended. – SergeantPenguin Dec 01 '15 at 23:34
  • 1
    Could be a compiler bug, these things are difficult to get right (and library writers say that the spec is a pain) – M.M Dec 02 '15 at 00:35

0 Answers0