mardi 1 décembre 2015

Can we make assumptions on the value of x if cin >> x fails? [duplicate]

This question already has an answer here:

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())?

Aucun commentaire:

Enregistrer un commentaire