2013-11-24 37 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; 
}