使用 ostringstream 或 stringstream,直接插入 bool 值:
bool b = true; ostringstream os; os << b; cout << os.str(); // "1" (預設輸出 1/0)
使用 boolalpha 操縱子:
ostringstream os; os << boolalpha << true;
cout << os.str(); // "true"
os.str(""); os << boolalpha << false;
cout << os.str(); // "false"
使用 istringstream 配合 boolalpha 讀取:
bool b;
istringstream("true") >> boolalpha >> b; // b = true
istringstream("false") >> boolalpha >> b; // b = false
#include#include using namespace std; int main() { // bool -> string ostringstream os1; os1 << true; cout << os1.str() << endl; // 1 ostringstream os2; os2 << false; cout << os2.str() << endl; // 0 ostringstream os3; os3 << boolalpha << true; cout << os3.str() << endl; // true ostringstream os4; os4 << boolalpha << false; cout << os4.str() << endl; // false // string -> bool bool b; istringstream("true") >> boolalpha >> b; cout << "b = " << b << endl; // 1 istringstream("false") >> boolalpha >> b; cout << "b = " << b << endl; // 0 return 0; }
1 0 true false b = 1 b = 0
bool 輸出為 1/0,需 boolalpha 才輸出文字。"true"/"false"(區分大小寫),否則讀取失敗。<sstream> 提供 ostringstream/istringstream/stringstream。