Reputation: 407
#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 input,the output will be 3+4=7
,well,it's strange;
But when I enter a b
,the output is 0+0=0
(Why it is 0 and 0?);
The most confusing,a 4
,it will be 0+0=0
(Why not '0+4=4'?????);
Then i write another prog.
#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
?
Thanks to all the warm-hearted!!
I write prog3,to test what will happen when i don't 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 a b
again,it outputs 0+-1218170892=-1218170892
(Why isn't 0+0=0
??)
Upvotes: 9
Views: 2550
Reputation: 16122
The value is set to zero on an error as per C++11: If extraction fails, zero is written to value and failbit is set.
On the 'a 4' example, both values are 0 because the buffer has not been flush/cleared, so the second cin read is still reading the error, and also receives a value of 0.
Upvotes: 3
Reputation: 4388
Like all istreams
, std::cin
has error bits. These bits are set when errors occur. For example, you can find the values of the error bits with functions like good()
, bad()
, eof()
, etc. If you read bad input (fail()
returns true
), use clear()
to clear the flags. You will also likely need an ignore(1);
to remove the offending character.
See the State functions
section for more information. http://en.cppreference.com/w/cpp/io/basic_ios
Upvotes: 4
Reputation: 31435
std::cin is an istream instance and thus it maintains its error state when it reads something invalid.
In order to "cure" it you must both clear its flag
std::cin.clear();
and flush its buffer.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
What is more surprising though is that it doesn't return 1 + 2 = 3 when you input invalid characters, as I would expect a failing cin stream to have no side effects on what it is trying to update.
Upvotes: 1