Search code examples
c++stdstdincinstdstring

Why is integer output 0 when collecting string from input


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?


Solution

  • 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