Output stream objects, cout, for example, maintain their current configuration or settings with a set of 1-bit flags. Programmers can dynamically (i.e., while a program is running) change the flags with the functions and symbolic constants illustrated in this section. The program demonstrates three stream member functions: setf (set flags), unsetf (unset flags), and flags, and three symbolic constants: ios::hex, ios::oct, and ios::dec. ios, sort for input/output system, is the name of a class, and :: is the scope resolution operator. Together, they bind the names hex, oct, and dec to the ios class - the class defining the constants.
Programmers use the flag functions and constants to adjust the base or radix in which the stream object displays data. Consequently, the operation setf(ios::dec | ios::oct | ios::hex) function, is meaningless as it's not possible to display data in multiple bases or radicies simultaneously. (Nevertheless, the statement compiles and runs without causing a runtime error, but its behavior is implementation-dependent.) Alternatively, the OR'ing the three flags together makes sense: unsetf(ios::dec | ios::oct | ios::hex) clears all three flags. The presence of ios::dec in the unsetf argument notwithstanding, the stream displays output in decimal until the hex manipulator in the next statement switches the stream to hexadecimal output.
Program | Output |
---|---|
#include <iostream> using namespace std; int main() { unsigned default_flags = cout.flags(); // gets the default formating flags cout << hex << default_flags << endl; cout.setf(ios::dec | ios::oct | ios::hex); // makes no sense cout << hex << cout.flags() << endl; cout.unsetf(ios::dec | ios::oct | ios::hex); // useful cout << 123 << endl; cout << hex << cout.flags() << endl; cout.flags(default_flags); // restores the default flags cout << hex << cout.flags() << endl; return 0; } |
201 = 0010 0000 0001 e01 = 1110 0000 0001 123 1 = 0000 0000 0001 201 = 0010 0000 0001 |
Compare to precision.cpp and base.cpp.