int a, b;
cin >> a >> b;
cout << a << endl << b;
input1: 3.5 5.5
input2: 3 5.5
The behaviour of your code is undefined up to and including C++03. The stream halts on the .
. From C++11 onwards b
is set to 0; prior to that it was not modified. Currently you read its value in the fail case, which is careless.
A good fix is to always write something like
if (cin >> a >> b){
// yes, all good
} else {
// a parsing error occurred
}
On the true
branch, values are guaranteed to have been written to a
and b
.
It reads:
So a
becomes 3
.
Then, when it tries to read the second number it is still at the .
, but a 'dot' is different from spaces and digits, so it does not consume any char and assignes 0
to b
and set the failbit
Thanks to @tobi303 for the specs link:
(until C++11) If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
(since C++11) If extraction fails, zero is written to value and failbit is set.
The input is not a decimal value; it's a text string, and the code will translate that text string into an integer value. So, what's the integer value that the string "3.5"
represents? It's 3, just as if the input had been "3 5"
: the code that translates the text reads as much of the text as makes sense, then stops. What happens after that depends on what caused the translation to stop. If it hit a whitespace character, all is well. If it hit something else (in this case, a .
), you're in trouble.