使用cin >>的C++中变量的默认值

Alb*_*rto 7 c++ c++11

我在CodeBlocks IDE中用C++编写了这段代码,但是当我运行它时,如果它没有读取数字,它就不会给我-1,它给了我0.代码是否有问题?

#include "iostream"

using namespace std;

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";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 11

std :: basic_istream :: operator >>的行为已从C++ 11更改.从C++ 11开始,

如果提取失败,则将零写入值并设置failbit.如果提取导致值太大或太小而不适合值,则写入std :: numeric_limits :: max()或std :: numeric_limits :: min()并设置failbit标志.

请注意,直到C++ 11,

如果提取失败(例如,如果输入了预期数字的字母),则值保持不变,并设置failbit.

您可以通过std :: basic_ios :: failstd :: basic_ios :: operator检查结果!并自己设置默认值.如,

string first_name;
if (!(cin>>first_name)) {
    first_name = "???";
    cin.clear(); //Reset stream state after failure
}

int age;
if (!(cin>>age)) {
    age = -1;
    cin.clear(); //Reset stream state after failure
}

cout<<"Hello, " <<first_name<<" (age "<<age<<")\n";
Run Code Online (Sandbox Code Playgroud)

另请参阅:重置流的状态