Problem with Input failure

I'm learning some first C++ lessons. In the Input/ouput section, according to the code on the book
1
2
3
4
5
6
7
8
9
10
11
  #include <iostream>
using namespace std;
int main()
{
	int a= 23;
	int b= 34;
	cout<<"Enter a number followed by a character: ";
	cin>>a>>b;
	cout<<endl<<"a= "<<a<<", b= "<<b<<endl;
	return 0;
}


Sample run in book: Enter a number followed by a character: 78 d
a=78, b=34


I knew b=34 since b is an int variable, so the value of b is unchanged. However, when I run this code on my computer, it doesn't run like the sample. I enter 78 d but the result is a=78, b=0. I tried with another input d 78 and the result is a=0, b=34. I think it would be a=23, d=78. I tried many inputs but they don't run as theory in the book.
I use Dev C++ 5.7.1
dont have any idea about it. its working fine on my codeblocks 13.12
The behavior of formatted input was chnged in C++11
(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. If extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() or std::numeric_limits<T>::min() is written and failbit flag is set.


In your second try, you read bad value in first variable (and it was set to 0). As failbit prevents all other input operation to work, second extraction is just skipped.

Also remember, that if input failed, whichever it failed on is still in the input buffer and will be encountered by next input operation.
This is one way to fix your problem:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
int main()
{
	int a;
	char b;
	cout<<"Enter a number followed by a character: ";
	cin>>a>>b;
	int c = b;
	cout<<endl<<"a= "<<a<<", b= "<<c<<endl;
	return 0;
}


my output was:
Enter a number followed by a character: 47 a

a= 47, b= 97
 
Last edited on
@MiiniPaa: Thank you. I got it. So the problem is the difference between my programming version and the book's version.
Topic archived. No new replies allowed.