在C++中,布尔变量只能包含两个不同的值,'true'或'false'。如果我们将这些值转换为字符串,'true'将映射为'1','false'将映射为'0'。布尔值主要用于检查程序中是否满足条件。与从int到long和float到double的转换不同,布尔到字符串没有直接的转换。但是有需要将布尔值转换为字符串的情况,我们将探讨不同的方法将二进制布尔值转换为字符串值。
使用三元运算符进行翻译
我们设计了一个算法,使用该算法我们可以检查提供的布尔变量的值,并根据该值输出“true”或“false”。输出是一个字符串变量,而输入是一个布尔值。我们使用三元运算符来确定输出,因为布尔值只有两个可能的取值。
语法
bool input = <Boolean value>;
string output = input ? "true" : "false";
算法
- 以布尔值作为输入;
- 如果布尔值为 true,则输出将为字符串“true”。
- 如果布尔输入值为 false,则输出值为“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或数据库方法可能不接受布尔值,因此使用这些方法我们可以将其转换为字符串值,因此也可以使用任何接受字符串值的方法。