2013-11-24 38 views
3

这可能看起来像一个愚蠢的问题,但我很难过。这里是我的代码:使用stringstream输入/输出布尔值

int main() 
{ 
    string line, command; 
    getline(cin, line); 
    stringstream lineStream(line); 

    bool active; 
    lineStream >>active; 
    cout <<active<<endl; 

} 

不管我输入了积极的,它总是打印出0。因此可以说,我的投入是

true 

它会输出0,同样的事情错误。

+0

IIRC'bool'需要特殊处理,有一些流处理器来控制它是如何解析的。默认值是查找“0”和“1”。 –

回答

12

您应该始终验证您的输入是否成功:您会发现它不是。你想尝试的价值1与当前设置:

if (lineStream >> active) { 
    std::cout << active << '\n'; 
} 
else { 
    std::cout << "failed to read a Boolean value.\n"; 
} 

如果你希望能够进入truefalse,你需要使用std::boolalpha

if (lineStream >> std::boolalpha >> active) { 
    std::cout << std::boolalpha << active << '\n'; 
} 

的格式标志变化bool的格式设置为使用依赖语言环境的字符串。

4

尝试使用boolalpha操纵器。

lineStream >> boolalpha >> active; 
cout << boolalpha << active << endl; 

默认情况下,流输入和输出bool值为微小的数字。 boolalpha告诉流使用字符串“true”和“false”来表示它们。

1

为ostringstream

ostringstream& writeBool(ostringstream& oss, bool val) 
{ 
    oss <<std::boolalpha << val; 

    return oss; 
} 

为istringstream解析时

bool readBool(std::istringstream& iss) 
{ 

    bool readVal(false); 

    iss >> std::boolalpha >> readVal; 

    return readVal; 
}