A Boolean value has two possible states: true and false, represented as 1 and 0. In C++, Boolean values can be converted to their textual representation using a custom function or the boolalpha stream manipulator.
- true and false represent the two Boolean states.
- boolalpha displays Boolean values as true or false instead of 1 or 0.
Examples:
Input:trueOutput:true
Input:falseOutput:false
Methods to Convert Boolean to String
The Boolean value can be converted to its string representation using the following approaches:
1. Using a Custom Conversion Function
Define a function that checks the Boolean value and returns the corresponding string.
#include <iostream>
#include <string>
using namespace std;
// Function to convert bool to string
string boolToString(bool value)
{
if (value)
return "true";
return "false";
}
int main()
{
bool value = true;
cout << boolToString(value) << endl;
return 0;
}
Output
true
Explanation: The boolToString() function checks the Boolean value and returns:
- "true" when the value is true.
- "false" when the value is false.
2. Using the boolalpha Stream Manipulator
By default, cout displays Boolean values as 1 and 0. The boolalpha manipulator changes this behavior to display true and false.
#include <iostream>
using namespace std;
int main()
{
bool value = true;
// Display bool as 1 or 0
cout << "Before boolalpha: "
<< value << endl;
// Display bool as true or false
cout << "After boolalpha: "
<< boolalpha << value << endl;
return 0;
}
Output
Before boolalpha: 1 After boolalpha: true
Explanation: Before applying boolalpha, cout displays the Boolean value as 1. After applying boolalpha, the same value is displayed as true.