Horje
Printing Boolean Values in C++

In C++, a boolean data type can only have two possible values true and false. However, when we print the boolean data types using the standard output streams like cout they are printed as 0 or 1 instead of true or false. In this article, we will learn how to print boolean values in C++ so that true and false are displayed on the output screen instead of 0 or 1.

Example

Input:
bool flag1= 1
bool flag2= 0

Output:
flag1: true
flag2: false

Print Boolean Values

To print boolean values in a more readable form, we can use the boolalpha flag provided by the Standard Template Library(STL) of C++. Following is the syntax to use the boolalpha flag:

Syntax

cout << std::boolalpha; // Enable boolalpha
cout << std::noboolalpha; // Disable boolalpha
  • std::boolalpha is used to set the output stream to print boolean values as true or false.
  • std::noboolalpha is used to revert the output stream to it’s default behavior.

C++ Program to Print Boolean Values

The following program illustrates how we can print the boolean values in a more readable format using the boolalpha flag in C++:

C++
// C++ Program to Print Boolean Values 
#include <iostream>
using namespace std;
int main() {
    // Initialize the boolean values
    bool flag1 = true;
    bool flag2 = false;
    
    cout<<"Booelan values with boolalpha flag enabled:"<<endl;
    // Enable boolalpha
    cout << boolalpha; 
    cout << "flag1: " << flag1 << endl;
    cout << "flag2: " << flag2 << endl;
    
    cout<<"Booelan values with boolalpha flag disabled:"<<endl;
    // Disable boolalpha
    cout << noboolalpha; 
    cout << "flag1: " << flag1 << endl;
    cout << "flag2: " << flag2 << endl;

    return 0;
}

Output
Booelan values with boolalpha flag enabled:
flag1: true
flag2: false
Booelan values with boolalpha flag disabled:
flag1: 1
flag2: 0

Time Complexity: O(1)
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
C++ Getters and Setters C++ Getters and Setters
Const Reference vs Normal Parameter Passing in C++ Const Reference vs Normal Parameter Passing in C++
How to Deallocate a 2D Array in C++? How to Deallocate a 2D Array in C++?
Why Const is Used at the End of Function Declaration in C++? Why Const is Used at the End of Function Declaration in C++?
Stack implementation in C++ Stack implementation in C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
8