Cin overwrites my initialized value when it reads the wrong type?

So this is really a basic question and super trivial, but I'm just looking at C ++ programming principles and practices and my inline and int reader behaves differently than the book written by Bjarne Stroustup, so id wondered if he's 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 type "22 Carlos" into the terminal when requested, it prints out "Hello, 22 (age 0)", basically rendering my error checking initialization value useless. Is this a new C ++ feature or something else, and why the book is wrong?

Edit1: BTW im using GCC for cygwin on Windows 7 and trigger -std = C ++ 11.

+3


source to share


2 answers


This is the new std :: basic_istream :: operator "> function , since C ++ 11:

If the extraction fails (for example, if a letter was entered in which a digit is expected), the value is left unchanged and the bitbit is set. (before C ++ 11)

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



Instead, you should check the status of the stream, eg.

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

      

+6


source


Try the following:

cin >> first_name >> age;  // read a string followed by an integer

//Check if cin failed.
if (cin.fail())
{
    //Handle the failure
}

      



As for why it sets the value to 0 after failing, take a look here:

Why does cin expecting an int change the corresponding int variable to zero in case of invalid input?

+3


source







All Articles