C++ provides data type bool
, whose values may be false
or true
, as a preferred alternative to the old style of using 0
to indicate false
and nonzero to indicate true
. A bool
variable outputs as 0
or 1
by default. However, we can use stream manipulator boolalpha to set the output stream to display bool
values as the strings "true"
and "false"
. Use stream manipulator noboolalpha to set the output stream to display bool
values as integers (i.e., the default setting). The program of Fig. 13.20 demonstrates these stream manipulators. Line 11 displays the bool
value, which line 8 sets to true
, as an integer. Line 15 uses manipulator boolalpha
to display the bool
value as a string. Lines 18–19 then change the bool
’s value and use manipulator noboolalpha
, so line 22 can display the bool
value as an integer. Line 26 uses manipulator boolalpha
to display the bool
value as a string. Both boolalpha
and noboolalpha
are sticky settings.
1 // Fig. 13.20: fig13_20.cpp
2 // Stream manipulators boolalpha and noboolalpha.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 bool booleanValue = true;
9
10 // display default true booleanValue
11 cout << "booleanValue is " << booleanValue << endl;
12
13 // display booleanValue after using boolalpha
14 cout << "booleanValue (after using boolalpha) is "
15 << boolalpha << booleanValue << endl << endl;
16
17 cout << "switch booleanValue and use noboolalpha" << endl;
18 booleanValue = false; // change booleanValue
19 cout << noboolalpha << endl; // use noboolalpha
20
21 // display default false booleanValue after using noboolalpha
22 cout << "booleanValue is " << booleanValue << endl;
23
24 // display booleanValue after using boolalpha again
25 cout << "booleanValue (after using boolalpha) is "
26 << boolalpha << booleanValue << endl;
27 } // end main
booleanValue is 1
booleanValue (after using boolalpha) is true
switch booleanValue and use noboolalpha
booleanValue is 0
booleanValue (after using boolalpha) is false
18.219.249.210