0
int a, b;
cin >> a >> b;
cout << a << endl << b;

input1: 3.5 5.5

input2: 3 5.5

check this code

Deepak Gautam
  • 1,309
  • 12
  • 14
  • Undefined behaviour is *undefined*. For the same input you may get a different set of output. Have a look.: https://code.sololearn.com/cvpv3mYy4Vbx/#cpp – Aditi Rawat Dec 19 '17 at 11:02

3 Answers3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 3
    afaik [since c++11 zero is written to the variable and the failbit is set if the operation fails](http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt), ie it isnt UB – 463035818_is_not_an_ai Dec 19 '17 at 10:42
  • it is not correct that b is unitialized after the read. in the code sample, try to initialize b to a num... after the read, it becomes 0 – Carlo Bellettini Dec 19 '17 at 11:21
  • @tobi303: Yes, C++11 indeed kindly sets the value to 0. (Personally I prefer the previous standards in this respect). – Bathsheba Dec 19 '17 at 11:28
3

It reads:

  • spaces/tabs/newlines (just consumes that if any)
  • digits till something different (the dot in your case) and parse them as the number

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. 
Carlo Bellettini
  • 1,130
  • 11
  • 20
0

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165