In C++, converting a boolean value (true/false) into a string can be achieved by leveraging the stringstream class. This particular class offers a mechanism for storing a string version of a given value. To perform the conversion, you can instantiate a stringstream object and input the boolean value into it. Subsequently, the stringstream will hold the string depiction of the boolean value, accessible through the str method.
Example snippet of code:
Std::ostringstream:
It is a commonly used library class that enables the transformation of values into strings. The std::ostringstream class functions as a stream designed for writing to a string. When converting a boolean value to a string, a std::ostringstream instance can be instantiated, the boolean value can be written to it employing the operator<<, and ultimately, the string can be retrieved using the str method.
#include <iostream>
#include <sstream>
int main() {
bool b1 = true;
bool b2 = false;
std::stringstream ss1, ss2;
ss1 << std::boolalpha << b1;
ss2 << std::boolalpha << b2;
std::string str1 = ss1.str();
std::string str2 = ss2.str();
std::cout << str1 << std::endl;
std::cout << str2 << std::endl;
return 0;
}
Output
true
false
We can also employ the to_string method in C++ to subsequently change boolean values to strings.
#include <iostream>
int main() {
bool b1 = true;
bool b2 = false;
std::string str1 = std::to_string(b1);
std::string str2 = std::to_string(b2);
std::cout << str1 << std::endl;
std::cout << str2 << std::endl;
return 0;
}
Output
The std::to_string function is responsible for converting a boolean into a string, displaying either "1" or "0". This behavior stems from the fact that in C++, booleans are essentially integers, where true is equivalent to 1 and false is equivalent to 0.
When employing std::to_string, the output string will not display "true" or "false". Instead, it will show either "1" or "0". For a string representation of "true" or "false", you can utilize the stringstream technique discussed previously.
A boolean value can be transformed into a string by utilizing the 'if' statement.
bool b = true;
std::string str = (b) ? "true" : "false";
In each of the previous instances, the boolean variable b is transformed into the string str, representing either "true" or "false".