Streams and Files - Tables for Text Manipulation (Page 3 of 4 )
Table 10-1 contains a summary of manipulators that operate on any kind of value (text, float, integer, etc.). There is a set of manipulators that apply only to floating-point output, and they are described in Recipe 10.2.
Table 10-1. Text manipulators
Manipulator
Description
Sample output
left
Justify values within the current field width to either the left or right side, and pad the remaining space with the fill character.
Left-justified:
apple bananna cherry
right
Right-justified (with a field width of 10 ):
apple
bananna
cherry
setw(int n)
Set the width of the field to n characters wide.
See earlier example.
Table 10-1. Text manipulations (continued)
Manipulator
Description
Sample output
setfill(int c)
Use the character cto pad fields that have remaining space.
cout << setfill('.') << setw(10) << right << "foo"
produces:
.......foo
boolalpha noboolalpha
Display Boolean values as the current locale’s representa-tion of the words trueand false, instead of 1and 0.
cout << boolalpha << true
produces:
true
endl
Write a newlineto the stream and flush the output buffer.
n/a
ends
Write a nullcharacter (‘\0’) to the stream.
n/a
flush
Flush the output buffer.
n/a
Some of the manipulators in Table 10-1 (and Table 10-2 in the next recipe) toggle binary stream flags, and are actually implemented as two manipulators that turn a flag on or off. Take boolalpha, for example. If you want Boolean values to be displayed as their written equivalents in the current locale (e.g., "true" and "false"), use the boolalpha manipulator. To turn this behavior off, so that 0 and 1 are printed instead, use noboolalpha, which is the default.
All manipulators have the behavior that they stay in effect until they are explicitly changed, except for setw. In Example 10-1, you can see that it is called before each write, but left is used only once. This is because the width is reset to zero after each value is written to the stream with operator<<; to keep the same width for each field, I had to call setw each time.
The standard manipulators provide a lot of functionality, but they don't do everything. If you want to write your own manipulators, see Recipe 10.2.