Thursday, May 20, 2010

Pretty printing boolean values in C++

By default boolean values (type bool, values true and false) are printed as 1 and 0 in C++ iostreams. There is a simple way to print them as their names (true/false). The following code-example demonstrates how to do that using boolalpha manipulator.

  1: #include <iostream>
  2: using namespace std;
  3: 
  4: int main()
  5: {
  6:     // By default true prints as 1 and false prints as 0
  7:     cout << true << " " <<  false << endl;
  8:     // We can enable boolalpha formatting flag 
  9:     cout << boolalpha;
 10:     // Now true and false will be inserted as their names instead
 11:     // of integral values
 12:     cout << true << " " <<  false << endl;
 13:     // We can later on unset boolalpha with noboolalpha format manipulator
 14:     cout << noboolalpha << endl;
 15:     cout << true << " " <<  false << endl;
 16:     // The boolalpha flag is not set in standard streams on initialization
 17:     return 0;
 18: }
 19: 
 20: 


The output of the program looks as follows:



  1: 1 0
  2: true false
  3: 1 0


We can notice that on the first line the output is integral. After setting boolalpha, the output becomes textual. Later on the output becomes integral again after setting noboolalpha.



Input streams



The manipulator can similarly be used on input streams for reading boolean values as true/false or 1/0.

No comments: