I have the following code snippet:
int a = 1;
double b = 3.14;
string c = "hi";
cin >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
If I enter apple 11 tammy
, why does it cout: 0 3.14 hi
instead of: 1 3.14 hi
?
Why does the value of a
change when cin
is broken?
Why does the value of
a
change whencin
is broken?
This is the expected behavior of std::basic_istream::operator>> since C++11; If extraction fails the value will be set to 0
.
If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value,
std::numeric_limits<T>::max()
orstd::numeric_limits<T>::min()
is written and failbit flag is set.
Note that after failbit
being set, the following input won't be performed; that means b
and c
will remain their original values.
BTW: Before C++11 the value will be left unmodified when extraction fails.
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.