Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
As you can see from the previous program, calling the member
functions for stream formatting operations can get a bit tedious. To make
things easier to read and write, a set of manipulators is supplied to
duplicate the actions provided by the member functions. Manipulators are a
convenience because you can insert them for their effect within a containing
expression; you don t need to create a separate function-call statement.
Manipulators change the state of the stream instead of (or
in addition to) processing data. When you insert endl in an output expression, for example, it not only inserts a newline character, but it also flushes
the stream (that is, puts out all pending characters that have been stored in
the internal stream buffer but not yet output). You can also just flush a stream like this:
which causes a call to the flush( ) member function, as in:
as a side effect (nothing is inserted into the stream).
Additional basic manipulators will change the number base to oct (octal), dec (decimal) or hex (hexadecimal):
cout << hex << "0x" << i << endl;
In this case, numeric output will continue in hexadecimal
mode until you change it by inserting either dec or oct in the
output stream.
There s also a manipulator for extraction that eats white
space:
Manipulators with no arguments are provided in <iostream>.
These include dec, oct, and hex, which perform the same
action as, respectively, setf(ios::dec, ios::basefield), setf(ios::oct,
ios::basefield), and setf(ios::hex, ios::basefield), albeit more
succinctly. The <iostream> header also includes ws, endl, and flush and the additional set shown here:
Manipulator
|
Effect
|
showbase
noshowbase
|
Indicate the numeric base (dec, oct, or hex)
when printing an integral value.
|
showpos
noshowpos
|
Show plus sign (+) for positive values.
|
uppercase
nouppercase
|
Display uppercase A-F for hexadecimal values, and display E
for scientific values.
|
showpoint
noshowpoint
|
Show decimal point and trailing zeros for floating-point
values.
|
skipws
noskipws
|
Skip white space on input.
|
left
right
internal
|
Left-align, pad on right.
Right-align, pad on left.
Fill between leading sign or base indicator and value.
|
scientific
fixed
|
Indicates the display preference for floating-point output (scientific
notation vs. fixed-point decimal).
|
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |