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

时间:2015-11-04 10:48:08

标签: 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;
}

2 个答案:

答案 0 :(得分:11)

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

  

如果提取失败,则将零写入值并设置failbit。如果   提取导致值太大或太小而无法适应   value,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";

另请参阅:Resetting the State of a Stream

答案 1 :(得分:0)

std::cin阅读时,不支持自定义默认值。您必须将用户输入作为字符串读取并检查它是否为空。有关详细信息,请参阅this question

引用相关问题:

int age = -1;
std::string input;
std::getline( std::cin, input );
if ( !input.empty() ) {
    std::istringstream stream( input );
    stream >> age;
}