0

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?

bcf
  • 2,104
  • 1
  • 24
  • 43

1 Answers1

1

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.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Do you know how I can see which version of C++ I'm using? I'm using g++ and in order to use other C++0x (same as C++11 I've heard?) features I've had to add -std=c++0x when compiling, so I'm not sure which one I used here. EDIT: Using g++ 4.6.3 – bcf Jan 02 '14 at 07:07
  • You should not rely on either behaviour anyway. Treat the value as indeterminate. – n. m. could be an AI Jan 02 '14 at 07:09
  • Yes, c++0x is the same as c++11, so you are using C++11. – n. m. could be an AI Jan 02 '14 at 07:16