C++程式將字串型別變數轉換為布林值


在C++中,布林變數包含二進位制資料true或false,字串變數是一系列字母、數字和特殊字元的序列。編譯器本身不支援字串到布林值的轉換,但有幾種方法可以執行此轉換。我們將探討各種方法,透過這些方法可以將字串值轉換為布林值。

如果我們考慮演算法,它非常簡單。我們獲取一個字串值,並使用各種方法將其轉換為布林值。

演算法(通用)

  • 在字串變數中獲取輸入。
  • 將字串值(true或false)轉換為布林值。
  • 輸出該值。

使用boolalpha和istringstream

Boolalpha是一個流I/O操縱器,可用於操縱布林值和字母數字值。Istringstream是一個字串流,用於在字元流上實現不同的函式。由於boolalpha與流一起使用,因此它可以與istringstream一起使用以將字串值轉換為布林值。

語法

string ip = <string literal>;
bool op;
istringstream(ip) >> std::boolalpha >> op;

演算法

  • 在字串變數中獲取輸入。
  • 將值放入istringstream物件中,並使用boolalpha將該值賦給布林變數。
  • 輸出該值。

示例

#include <iostream> #include<sstream> using namespace std; bool solve(string ip) { bool op; istringstream(ip) >> std::boolalpha >> op; return op; } int main() { string ip = "true"; bool op = solve(ip); cout << "The value of ip is: " << ip <<endl; cout << "The value of op is: " << op <<endl; return 0; }

輸出

The value of ip is: true
The value of op is: 1

在此示例中,我們獲取了一個字串值作為輸入。然後,我們使用istringstream物件來包含字串值,然後使用boolalpha修飾符將其轉換為布林變數。我們列印輸入和輸出值以進行比較。

使用字串比較

在下一個示例中,我們進行了基本的字串比較以將字串值轉換為布林值。如果字串值等於“false”,則返回0;否則,返回1。需要注意的是,這將為除“false”以外的所有字串返回true。但是這種方法是最容易實現的。

語法

string ip = <string literal>;
bool op = ip != “false”;

演算法

  • 在字串變數ip中獲取輸入。
  • 獲取一個布林變數op。
  • 如果ip與“false”相同,則
    • op = false
  • 否則,
    • op = true
  • 顯示op的值。

示例

#include <iostream> using namespace std; bool solve(string s) { return s != "false"; } using namespace std; int main() { string ip = "true"; bool op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }

輸出

The input value is: true
The output value is: 1

使用std::stoi

在前面的示例中,我們只將“true”轉換為布林值1,將“false”轉換為布林值“0”。現在,在某些情況下,字串值可能是0或1。對於這種情況,我們可以使用stoi函式將字串值轉換為整數,然後轉換為布林值。stoi函式將字串值轉換為整數,並使用顯式型別轉換,我們可以將該值轉換為布林值。

語法

string ip = <string literal>;
bool op = (bool)stoi(ip);

演算法

  • 在字串變數ip中獲取輸入。
  • 獲取一個布林變數op。
  • 將值顯式型別轉換為stoi(ip)的結果的bool。
  • 顯示op的值。

示例

#include <iostream> #include <string> using namespace std; bool solve(string s) { //using std:: stoi function return (bool)stoi(s); } using namespace std; int main() { string ip = "1"; bool op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }

輸出

The input value is: 1
The output value is: 1

結論

我們獲取了作為輸入的字串,這些字串可能包含“true”、“1”、“false”或“0”中的任何值。前兩種方法分別將“true”或“false”轉換為1和0。如果我們將“true”或“false”替換為“1”或“0”,它將以相同的方式工作。但在第三個示例中,如果我們將“1”或“0”更改為“true”或“false”,它將不起作用,因為stoi函式無法將不包含字母數字字元的字串轉換為整數值,因此無法轉換為布林值。因此,根據使用情況,我們必須確定要使用的最佳方法。

當在特定專案中使用某些第三方庫或API時,需要進行字串到布林值的轉換。一些API或庫以字串格式輸出,為了使結果相容,我們必須將字串值轉換為布林值。

更新於: 2022年10月19日

6K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.