首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ bool 與 string 互轉:stringstream 與 boolalpha 完整用法

     編輯:C++ 入門

C++ bool 與 string 互轉完整指南

bool → string

使用 ostringstream 或 stringstream,直接插入 bool 值:

bool b = true;
ostringstream os; os << b;
cout << os.str(); // "1" (預設輸出 1/0)

輸出 "true"/"false" 文字

使用 boolalpha 操縱子:

ostringstream os; os << boolalpha << true;
cout << os.str(); // "true"
os.str(""); os << boolalpha << false;
cout << os.str(); // "false"

string → bool

使用 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。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved