2015-11-04 79 views
7

我已经在CodeBlocks IDE的C++中编写了这段代码,但是当我运行它时,如果它不读取数字,它不会给我-1,它会给我0.代码有问题吗?使用cin的C++变量的默认值>>

#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

的'操作符<<()'将设置'age'到它的默认值(即'0'在这种情况下),并覆盖'-1'当它不能读取一个数字。这是正常的行为。 –

+1

@πάνταῥεῖ你的意思是'operator >>',对吧? – Angew

+1

http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt Quote:'自C++ 11:如果提取失败,零写入值和失败位被设置' – bolov

回答

11

std::basic_istream::operator>>行为已经从C++ 11改变。由于C++ 11,

如果提取失败,则将零写入值并设置失败位。如果 提取的结果值太大或太小而不适合 值,则写入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

我会解释OP如何检查failbit(然后设置默认值)。我还会指出他[在这里:重置流的状态](http://stackoverflow.com/questions/11246960/resetting-the-state-of-a-stream) – Antonio

+0

我认为OP更有兴趣设置在这种情况下的默认值。 (我也会重置流的状态) – Antonio

+0

谁是OP?为什么当我要求我的一个朋友在Visual Studio 2015中编写完全相同的代码时,如果它没有读取数字,它会给他“-1”?这是关于IDE的东西吗? @songyuanyao – Alberto

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