cin overwriting my initialized value when it reads

2020-04-09 04:11发布

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.

2条回答
家丑人穷心不美
2楼-- · 2020-04-09 04:48

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 ...
}
查看更多
Evening l夕情丶
3楼-- · 2020-04-09 04:51

Try this:

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

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

As to why it sets the integer to 0 upon failure, have a look here:

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

查看更多
登录 后发表回答