C++程序将布尔变量转换为字符串


C++中的布尔变量只能包含两个不同的值,'true'或'false'。如果我们将这些值转换为字符串,'true'将映射到'1','false'将映射到'0'。布尔值主要用于检查程序中的某个条件是否满足。我们没有像从int到long和float到double的转换那样,直接从布尔值到字符串的转换。但需要将布尔值转换为字符串,我们探讨了将二进制布尔值转换为字符串值的几种不同方法。

使用三元运算符进行转换

我们设计了一种算法,使用该算法检查提供的布尔变量的值,然后根据该值输出'true'或'false'。输出是一个字符串变量,而输入是一个布尔值。我们使用了三元运算符来确定输出,因为只有两个布尔值。

语法

bool input = <Boolean value>;
string output = input ? "true" : "false";

算法

  • 将布尔值作为输入;
  • 如果布尔值为真,则输出将为字符串'true'。
  • 否则,如果布尔输入值为假,则输出值将为'false'。

示例

#include <iostream> using namespace std; string solve(bool input) { //using ternary operators return input ? "true" : "false"; } int main() { bool ip = true; string 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: true

输入值存储在变量ip中,转换操作在函数solve()中完成。函数的输出存储在一个字符串变量中,该变量为op。我们可以看到这两个变量的输出。输出中的第一个值是在转换之前,输出中的第二个值是在转换之后。

在字符串输出时使用std::boolalpha

boolalpha是一个I/O操纵器,因此可以在流中使用。我们将讨论的第一种方法无法使用此方法将布尔值分配给字符串变量,但我们可以使用它以输入/输出流中的格式输出它。

语法

bool input = <Boolean value>;
cout<< "The output value is: " << boolalpha << input << endl;

算法

  • 将布尔值作为输入。
  • 使用boolapha修饰符显示布尔值作为输出。

示例

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

输出

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

在上面的示例中,我们可以看到,如果我们使用cout输出布尔变量的值,输出为0或1。当我们在cout中使用boolalpha时,我们可以看到输出更改为字符串格式。

使用std::boolalpha并将其分配给变量

在前面的示例中,我们只是修改了输出流以获取布尔值的字符串输出。现在我们看看如何使用它将字符串值存储在变量中。

语法

bool input = <Boolean value>;
ostringstream oss;
oss << boolalpha << ip;
string output = oss.str();

算法

  • 将布尔值作为输入。
  • 使用boolalpha修饰符将输入值放入输出流对象中。
  • 返回输出流对象的字符串格式。

示例

#include <iostream> #include <sstream> using namespace std; string solve(bool ip) { //using outputstream and modifying the value in the stream ostringstream oss; oss << boolalpha << ip; return oss.str(); } int main() { bool ip = false; string op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }

输出

The input value is: 0
The output value is: false

与前面的示例不同,我们将输入布尔值放入输出流中,然后将其转换为字符串。solve()函数返回一个字符串值,我们在字符串函数中将该值存储在op变量中。

结论

我们讨论了将二进制布尔值转换为字符串的各种方法。当我们处理数据库或与某些基于Web的API交互时,这些方法很有用。API或数据库方法可能不接受布尔值,因此使用这些方法,我们可以将其转换为字符串值,因此任何接受字符串值的方法也可以使用。

更新于: 2022年10月19日

4K+浏览量

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.