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?

7
  • 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. Commented Jul 21, 2018 at 7:54
  • Just check how to recover from stream failed state due to invalid inputs. Commented Jul 21, 2018 at 7: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. Commented Jul 21, 2018 at 7: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. Commented Jul 21, 2018 at 8:02
  • 1
    You can always refer to the documentation before asking here, sorry. Commented Jul 21, 2018 at 8:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.