What does cin do when there is an error

#include<iostream>; int main() { int a = 1; int b = 2; std::cin >> a >> b; std::cout << a << "+" << b << "=" << a+b << std::endl; return 0; } 

when I enter 3 4 as an input, the output will be 3+4=7 , well, this is strange; But when I enter ab , the output is 0+0=0 (why is it 0 and 0?); The most confusing, a 4 , it will be 0+0=0 (why not "0 + 4 = 4" ?????); Then I write another program.

 #include<iostream>; int main() { int a = 1; int b = 2; std::cin >> a; std::cin.clear(); std::cin >> b; std::cout << a << "+" << b << "=" << a+b << std::endl; return 0; } 

When I enter a 4 , why is it still 0+0=0 ? Shouldn't it be 0+4=4 ?

Thank you all heartfelt !!

I write prog3 to check what happens when I do not write int a=1;int b=2 ;

 2 #include <iostream> using namespace std; int main() { int a,b; cin >> a ; cin >> b; cout<< a << "+"<< b <<"="<< a+b << endl; return 0; } 

When ab again, it gives 0+-1218170892=-1218170892 (why not 0+0=0 ?)

+8
c ++ error-handling cin
source share
3 answers

Like all istreams , std::cin has an error bit. These bits are set when errors occur. For example, you can find error bit values ​​with functions such as good() , bad() , eof() , etc. If you read bad input ( fail() returns true ), use clear() to clear the flags. You will also probably need ignore(1); to remove the offensive character.

See State functions more information. http://en.cppreference.com/w/cpp/io/basic_ios

+1
source share

std :: cin is an istream instance, and therefore it retains its error state when reading something invalid.

To "cure" him, you must how to clear your flag

 std::cin.clear(); 

and flush its buffer.

 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

What is more surprising is that it does not return 1 + 2 = 3 when entering invalid characters, since I expect the bad cin stream to have no side effects on what it is trying to update.

0
source share

The value is set to zero with an error in accordance with C ++ 11: if the extraction failed, zero is written to the value and set to failbit.

In the "a 4" example, both values ​​are 0 because the buffer has not been flushed / flushed, so the second read of cin still reads the error, and also gets the value 0.

0
source share

All Articles