cin overwriting my initialized value when it reads wrong type?

c++, c++11, cin, language-lawyer

Solution

This is a new feature of std::basic_istream::operator>> since C++11:

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)

You should check the status of stream instead, e.g.

if (cin >> age) {
    ... fine ....
} else {
    ... fails ...
}

Problem

So this is a really basic question and super trivial but Im just going through programming principles & practices in c++ and my program for reading in a string and a int is behaving differently than the book which is written by Bjarne Stroustrup so id be surprised if he made a mistake. Anyway here's the code: ``` #include "..\std_lib_facilities.h" int main() { cout << "Please enter your first name and age\n"; string first_name = "???"; // string variable // ("???” means “don’t know the name”) int age = -1; // integer variable (1 means “don’t know the age”) cin >> first_name >> age; // read a string followed by an integer cout << "Hello, " << first_name << " (age " << age << ")\n"; } ``` When I input "22 Carlos" into the terminal at prompt it outputs "Hello, 22 (age 0)" basically making my initialization value for error checking useless. Is this a new feature of c++ or something and thats why the book is wrong? Edit1: BTW im using GCC for cygwin on windows 7 and the -std=c++11 trigger.

Original source

Related problems