cin not behaving as expected

Oct 21, 2015 at 4:38pm
Hi,
I'm passing cin some erroneous input, but it's not failing as expected. The code is just:
1
2
3
4
5
  cout << "Please enter an integer: ";
  int n = 0;
  cin >> n;
  cout << "Got : " << n << "\n";
  if (cin.fail()) cout << "cin was left in failed state.\n";


When I give an input that begins with an integer, but also then contains non-numeric characters, I don't get a failed state, e.g.:

$ ./a.out
Please enter an integer: 44ffffff
Got : 44
$

It's as if it's delimiting on the first non-numeric character it comes across, rather than just whitespace. Can anyone explain why please? I'm using g++ (v4.9.2) under Debian "jessie".
Oct 21, 2015 at 4:40pm
As far as I remember that is compiler dependent, undefined territory.

In other words don't rely on that functionality even if it does have a consistent behavior. I would expect the results to be inconsistent. (If you want it to work the way you expect you could parse the values from the string and handle your exceptions in whatever way you want)
Last edited on Oct 21, 2015 at 4:42pm
Oct 21, 2015 at 4:53pm
It's as if it's delimiting on the first non-numeric character it comes across, rather than just whitespace. Can anyone explain why please?

Because that is the way the C++ streams were designed, much like their C-stdio counterparts. The processing of a number will stop when a non-digit is encountered. The only time the stream will fail is if the first character is not either the sign (+-) or a digit. If any valid numeric character is encountered before any invalid character, the stream will be in a "good" state and the remaining characters will be left in the input buffer for further processing.

As far as I remember that is compiler dependent, undefined territory.

No it is well defined and specified by the standard.
Last edited on Oct 21, 2015 at 4:54pm
Oct 21, 2015 at 6:14pm
Thanks for the clarification.
Oct 22, 2015 at 12:22am
No it is well defined and specified by the standard.


Well guess I have beans for memory xD
Topic archived. No new replies allowed.