Reputation: 2134
I thought that, if cin
enters an error state, the variable it is streaming into remains unchanged. However, the following seems to be a counterexample:
#include <iostream>
using namespace std;
int main()
{
cout << "Enter int: ";
int i = 5;
cin >> i;
if(cin.fail()) cout << "failed \n";
cout << "You entered: " << i << "\n";
}
Running:
Enter int: g
failed
You entered: 0
Where did I go oh so wrong?
Upvotes: 0
Views: 199
Reputation: 119847
The behaviour has changed in C++11. Failed integer extraction now sets the variable to 0.
GCC 4.8 exhibits the new behaviour even without -std=c++11
flag, which is probably a bug/limitation of the library. There's only one libstdc++, and it doesn't know which compiler flags were used to compile main
.
Upvotes: 1