Open In App

C++ Program For Boolean to String Conversion

Last Updated : 04 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to convert a boolean to a string using a C++ program.

In boolean algebra, there are only two values 0 and 1 which represent False and True. Thus, boolean to string conversion can be stated as:

Boolean -> String

  • 1 -> True
  • 0 -> False

Example:

Input: 1
Output: True

Methods to Convert a Boolean to a String in C++

There are 2 ways to convert boolean to string in C++:

  1. Using Customized Boolean To String Conversion Function.
  2. Using Alphanumeric Boolean Values.

Let’s discuss each of these methods in detail.

1. Boolean To String Conversion Using Customized Function

We have defined a customized boolean-to-string conversion function btos(). It is responsible for converting a boolean value into its corresponding string representation.

C++ Program to Convert Boolean Values to String

C++




// C++ program to convert
// truth table for OR operation
#include <iostream>
using namespace std;
  
// Function to convert boolean
// into string
string btos(bool x)
{
    if (x)
        return "True";
    return "False";
}
  
// Driver code
int main()
{
    // Conversion of Truth Table
    // for OR operation
    cout << 1 << " || " << 0 << " is " << btos(1 || 0)
         << endl;
    cout << 1 << " && " << 0 << " is " << btos(1 && 0)
         << endl;
  
    return 0;
}


Output

1 || 0 is True
1 && 0 is False

Complexity Analysis

  • Time complexity: O(1)
  • Auxiliary space: O(1)

2. Using Alphanumeric Boolean Values

The boolalpha flag indicates whether to use textual representation for bool values viz true or false or to use integral values for bool values viz 1 or 0. When the boolalpha flag is set, the textual representation is used and when it is not set, integral representation is used. By default, it is not set.

C++ Program to Convert a Boolean to a String Using boolalpha Flag

C++




// C++ program to convert boolean
// to string using boolalpha flag
#include <iostream>
using namespace std;
  
// Driver code
int main()
{
    bool value = true;
  
    cout << "Printing true value before boolalpha: "
         << value << endl;
    cout << "Printing true value after boolalpha: "
         << boolalpha << value << endl;
  
    return 0;
}


Output

Printing true value before boolalpha: 1
Printing true value after boolalpha: true

Complexity Analysis

  • Time complexity: O(1)
  • Auxiliary space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads