简体   繁体   中英

C++ : Unexpected output

I have the below code:

int a , b , sum;
cin>>a>>b;
sum=a+b;
cout<<sum;

I am completely aware that you cannot store floating point values in an integer. So during the first run of my program:

10 2.5

12

I get the expected output of 12 as the decimal part of 2.5 is ignored

In the second run I put the floating point value first:

2.5 10

442837

I get a garbage value , anyone knows what going on?

Help is appreciated :)

Initialize your variables and you will see what is happening. It isn't ignore the decimal. It is causing an error that stops the parsing. So the crazy number you see is actually the value of the uninitialized integer.

Here is what is happening: When you type "10 2.5" it puts 10 into a, and 2 into b. It does not ignore th e 0.5. To understand what actually happens, try this code:

int a=100 , b=200 , c=300, sum;
cin>>a>>b>>c;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;

Then enter in "10 2.5" and a will be 10, b will be 2, and c will be 300! The ".5" caused cin to get an error, and so it just left c at the default value. But since you only read 2 values, it seemed to work just fine. So try that version with your second set of inputs "2.5 10". A will be 2, then b will be 200 and c will be 300. That shows how cin encountered an error when it saw the decimal point, and just gave up.

And finally for fun, remove the initializations in my example, and watch how you get crazy values for b and c.

Quote from std::istream::operator>> :"Extracts and parses characters sequentially from the stream to interpret them as the representation of a value of the proper type, which is stored as the value of val."

Check the std::istream::operator>> for an in depth look at how reading the input works.

Moreover, you could std::cout << std::cin.rdstate(); after reading a double value into an int, to see that the cin object gets into an error state at such an operation. The answer I think, is that cin >> operation does not do implicit type conversions, and is thrown into an error state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM