Printing Boolean Values in C++

Suraj P Oct 12, 2023
  1. Boolean Value as true/false in C++
  2. Modify the printf() by Adding a Ternary Statement to Print Boolean Values in C++
  3. Use std::boolalpha in cout to Print Boolean Values in C++
  4. Use Custom Facet for std::numpunc to Print Boolean Values in C++
  5. Conclusion
Printing Boolean Values in C++

When working with C++, Boolean values are printed as 0 for false and 1 for true when using std::cout. In some situations, it’s more readable and informative to display Boolean values in the textual form of true or false.

This article explores various methods to achieve printing Boolean values in C++.

Boolean Value as true/false in C++

Let’s assume a scenario where we read through lines and lines of code and log files while debugging, and now it’s very easy to miss a 0 or a 1 in a sea of errors and numbers. So it’s better to have the bool value printed as true/false.

We will show three different ways to achieve this.

Modify the printf() by Adding a Ternary Statement to Print Boolean Values in C++

One of the simplest ways to print Boolean values as true or false is by making a modification to the printf() function. When printing Boolean values using printf(), you usually use the format specifier %d since there is no dedicated format specifier for Boolean values.

Since a bool is promoted to an int when passed to printf(), this approach results in plain 0 and 1 output. To change this to true or false, you can add a ternary if-statement and change the format specifier to %s.

Example Code:

#include <iostream>
using namespace std;
int main()

{
  printf("boolean true: %d\n", true);    // Print 'true' as numeric value (1).
  printf("boolean false: %d\n", false);  // Print 'false' as numeric value (0).

  // Modified printf() statements to improve output readability:
  // Print 'true' as text if true; otherwise, print 'false' as text.
  printf("boolean true: %s\n", true ? "true" : "false");

  // Print 'false' as text if false; otherwise, print 'false' as text.
  printf("boolean false: %s\n", false ? "true" : "false");
}

Output:

boolean true: 1
boolean false: 0
boolean true: true
boolean false: false

While this method enhances code readability, it might not be the best choice for large and complex source code files, as it can hinder readability.

Use std::boolalpha in cout to Print Boolean Values in C++

The std::boolalpha manipulator can be found in the <iomanip> header file, and it works with input and output stream functions. The standard streams in C++ have a boolalpha flag that determines what gets printed on the screen.

When this flag is set to true, it displays the textual form of Boolean values, i.e., true or false. However, when set to false, it reverts to displaying Boolean values as 0 and 1.

Example Code:

#include <iostream>
using namespace std;

int main() {
  cout << "when boolalpha flag is off" << endl;  // Print a header message.
  cout << "true: " << true << endl;    // Display 'true' as numeric value (1).
  cout << "false: " << false << endl;  // Display 'false' as numeric value (0).

  cout << "when boolalpha flag is on" << endl;  // Print another header message.
  cout << boolalpha << "true: " << true
       << endl;  // Enable boolalpha, display 'true' as text.
  cout << boolalpha << "false: " << false
       << endl;  // Enable boolalpha, display 'false' as text.

  cout << noboolalpha;  // Turn off boolalpha flag to restore default behavior.
  // From this point, boolean values will be displayed as numeric (0 or 1).
  // Continue here with the default behavior for boolean values.
  return 0;
}

Output:

when boolalpha flag is off
true: 1
false: 0
when boolalpha flag is on
true: true
false: false

As shown in the example, enabling the boolalpha flag using cout << boolalpha allows Boolean values to be displayed in their more intuitive textual form. This improves the clarity of your program’s output.

While std::boolalpha is a useful tool, it has some limitations. It’s essential to turn off the boolalpha flag after using it via cout << noboolalpha.

Additionally, if you need to print Boolean values in languages other than English or use custom words like "hai" and "nai" for true and false, or even capitalize them as True and False, std::boolalpha alone may not provide these capabilities.

Use Custom Facet for std::numpunc to Print Boolean Values in C++

If you need to display something other than true or false for Boolean values, you can achieve this using a custom std::numpunct facet.

In C++, a facet is a class that defines the locale-specific behavior for various aspects of I/O. Stream input and output operations use std::numpunct through std::numget and std::numput for parsing numeric input and formatting numeric output.

The std::numpunct facet encapsulates numeric punctuation preferences, including Boolean values. To customize the output for Boolean values when the std::boolalpha flag is active, you can override the do_truename() and do_falsename() functions provided by std::numpunct.

Example Code:

#include <ios>
#include <iostream>
#include <locale>
using namespace std;

// Define a custom class 'japanese_bool' that inherits from
// 'std::numpunct<char>'.
class japanese_bool : public std::numpunct<char> {
 protected:
  // Override the 'do_truename' function to specify the custom string for
  // 'true'.
  std::string do_truename() const override { return "Hai"; }

  // Override the 'do_falsename' function to specify the custom string for
  // 'false'.
  std::string do_falsename() const override { return "NAI"; }
};

int main() {
  // Create a locale object with the custom 'japanese_bool' facet and imbue it
  // into 'cout'.
  cout.imbue(std::locale(std::locale(), new japanese_bool));

  // Enable the 'std::boolalpha' flag to display boolean values as text.
  cout << std::boolalpha;

  // Print a custom message along with 'true' and 'false' values.
  cout << "Japanese true : " << true << "\n";
  cout << "Japanese false : " << false << "\n";

  // Turn off the 'std::boolalpha' flag to revert to the default numeric
  // representation.
  cout << noboolalpha;
}

The use of new does not result in a memory leak because the customNames object is implicitly reference-counted. When the std::locale object referencing it goes out of scope, it will be automatically destroyed.

Output:

Japanese true : Hai
Japanese false : NAI

Conclusion

This article has explored different methods to print Boolean values in C++ as true and false. The first two methods are preferable when you want to enhance the readability of your code by displaying true or false as output.

However, the third method, using a custom facet for std::numpunct, is the way to go when you need specialized output for Boolean values beyond the standard true and false. Understanding these methods empowers you to make your C++ code more accessible and user-friendly.

Author: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub