This tutorial introduces ANSI/ISO C++'s stream formatting capabilties, including stream manipulators, justification, padding, integer formats, floating-point number formats, uppercase/lowercase control, formatting booleans as strings, and setting and restoring stream format states. This tutorial is intented for students and developers who are familiar with basic C++ input and output techniques using cin and cout. The techniques shown here can also be applied to file-based streams or other streams that extend the standard C++ stream class hierarchy.
Download the code examples for this tutorial.
[Note: This tutorial is an excerpt (Section 15.7) of Chapter 15, Stream Input/Output, from our textbook C++ How to Program, 5/e. These tutorials may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., C++ HOW TO PROGRAM, ©2005, pp.787-797. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]
15.7 Stream Format States and Stream Manipulators (Continued)
15.7.8 Setting and Resetting the Format State via Member Function flags
Throughout Section 15.7, we have 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 a fmtflags data type (of class ios_base), which represents the format state. Member function flags with a 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. 15.21 uses member function flags to save the stream’s original format state (line 22), then restore the original format settings (line 30).
|
||
| Fig. 15.21 | flags member function. |
|
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 |
Other sections in this tutorial:
Introduction to Stream Format States and Stream Manipulators
15.7.1 Trailing Zeros and Decimal Points (showpoint)
15.7.2 Justification (left, right and internal)
15.7.3 Padding (fill, setfill)
15.7.4 Integral Stream Base (dec, oct, hex, showbase)
15.7.5 Floating-Point Numbers; Scientific and Fixed Notation (scientific, fixed)
15.7.6 Uppercase/Lowercase Control (uppercase)
15.7.7 Specifying Boolean Format (boolalpha)
15.7.8 Setting and Resetting the Format State via Member Function flags (You are here).

