13.7.8. Setting and Resetting the Format State via Member Function flags

Throughout Section 13.7, we’ve been using stream manipulators to change output format characteristics. We now discuss how to return an output stream’s format to its default state after having applied several manipulations. Member function flags without an argument returns the current format settings as an fmtflags data type (of class ios_base), which represents the format state. Member function flags with an fmtflags argument sets the format state as specified by the argument and returns the prior state settings. The initial settings of the value that flags returns might differ across several systems. The program of Fig. 13.21 uses member function flags to save the stream’s original format state (line 17), then restore the original format settings (line 25).


 1   // Fig. 13.21: fig13_21.cpp
 2   // flags member function.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main()
 7   {
 8      int integerValue = 1000;
 9      double doubleValue = 0.0947628;
10
11      // display flags value, int and double values (original format)
12      cout << "The value of the flags variable is: " << cout.flags()
13         << " Print int and double in original format: "
14         << integerValue << ' ' << doubleValue << endl << endl;
15
16      // use cout flags function to save original format     
17      ios_base::fmtflags originalFormat = cout.flags();      
18      cout << showbase << oct << scientific; // change format
19
20      // display flags value, int and double values (new format)
21      cout << "The value of the flags variable is: " << cout.flags()
22         << " Print int and double in a new format: "
23         << integerValue << ' ' << doubleValue << endl << endl;
24
25      cout.flags( originalFormat ); // restore format
26
27      // display flags value, int and double values (original format)
28      cout << "The restored value of the flags variable is: "
29         << cout.flags()
30         << " Print values in original format again: "
31         << integerValue << ' ' << doubleValue << endl;
32   } // end main


The value of the flags variable is: 513
Print int and double in original format:
1000    0.0947628

The value of the flags variable is: 012011
Print int and double in a new format:
01750   9.476280e-002

The restored value of the flags variable is: 513
Print values in original format again:
1000    0.0947628


Fig. 13.21. flags member function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.113.147