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 07: cout << true << " " << false << endl;8: // We can enable boolalpha formatting flag9: cout << boolalpha;10: // Now true and false will be inserted as their names instead11: // of integral values12: cout << true << " " << false << endl;13: // We can later on unset boolalpha with noboolalpha format manipulator14: cout << noboolalpha << endl;15: cout << true << " " << false << endl;16: // The boolalpha flag is not set in standard streams on initialization17: return 0;18: }19:20:
The output of the program looks as follows:
1: 1 02: true false3: 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:
Post a Comment