2

I'm new to C++ and am working through Stroustrup's Programming Principles and Practices. In section 3.3, he gives the following example:

#include <iostream>
#include <string>

int main() {
  std::cout << "Please enter your first name and age\n";
  std::string firstName;
  int age;
  std::cin >> firstName >> age;
  std::cout << "Hello, " << firstName << " (age " << age << ")\n";
}

As per the text, I entered '22 Carlos' and expect the output to be 22 followed by some random number or 0. Fine, I get 0.

I then initialise the variables and input the same '22 Carlos':

string firstName = "???";
int age = -1;

I expect the output to be 'Hello, 22 (age -1)', as stated in the text, but instead get 'Hello, 22 (age 0)'. Why?

SuperWill
  • 9
  • 5
junglie85
  • 1,243
  • 10
  • 30
  • Because your STL's implementation of `operator>>` is explicitly setting invalid int input to 0. That is allowed,though the behavior was undefined prior to C++11, but is guaranteed in C++11 and later. – Remy Lebeau Jul 21 '18 at 07:54
  • Just check how to recover from stream failed state due to invalid inputs. – πάντα ῥεῖ Jul 21 '18 at 07:56
  • @πάνταῥεῖ it's not a duplicate question as linked. I'm asking why the disparity between the book and the actual output, the linked question is asking if anyone uses the extraction operator. Totally different. – junglie85 Jul 21 '18 at 07:59
  • Whoever closed this question as a duplicate didn't read the answers to the duplicate, because NONE of them answer this question. So I'm reopening this question. – Remy Lebeau Jul 21 '18 at 08:02
  • 1
    You can always refer to the [documentation](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2) before asking here, sorry. – πάντα ῥεῖ Jul 21 '18 at 08:03
  • @Remy Whoever wrote that question didn't bother to research. – πάντα ῥεῖ Jul 21 '18 at 08:04
  • It's wrong, string cannot receive input from cin. Use getline; – Dennys Barreto Jul 21 '18 at 17:09

1 Answers1

3

The reason why you get age set to 0 is because (assuming you are on c++11 or higher):

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. (until C++11)

If extraction fails, zero is written to value and failbit is set. (since C++11)

Just a side note, VC++ compiler was not following this standard until recently https://developercommunity.visualstudio.com/content/problem/285201/the-value-is-not-zeroed-after-failure-but-it-shoul.html

Community
  • 1
  • 1
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37