Working with Streams 615
17
One if by land
One if by
One if by land i?!
OUTPUT
The final line of output might look different on your computer because it
accesses memory that is not part of an initialized variable.
NOTE
This listing prints from a phrase. Each time it prints a different amount of the
phrase. On line 7, one phrase is created. On line 9, the integer fullLengthis set
to the length of the phrase using a global strlen()method that was included with the
string directive on line 2. Also set are two other length values that will be used; tooShort
is set to the length of the phrase (fullLength)minus four, and tooLongis set to the
length of the phrase plus six.
On line 13, the complete phrase is printed using write(). The length is set to the actual
length of the phrase, and the correct phrase is printed.
On line 14, the phrase is printed again, but it is four characters shorter than the full
phrase, and that is reflected in the output.
On line 15, the phrase is printed again, but this time write()is instructed to write an
extra six characters. After the phrase is written, the next six bytes of contiguous memory
are written. Anything could be in this memory, so your output might vary from what is
shown previously.
Manipulators, Flags, and Formatting Instructions ........................................
The output stream maintains a number of state flags, determining which base (decimal or
hexadecimal) to use, how wide to make the fields, and what character to use to fill in
fields. A state flag is a byte whose individual bits are each assigned a special meaning.
Manipulating bits in this way is discussed on Day 21, “What’s Next.” Each of ostream’s
flags can be set using member functions and manipulators.
Using cout.width()
The default width of your output will be just enough space to print the number, character,
or string in the output buffer. You can change this by using width().
Because width()is a member function, it must be invoked with a coutobject. It only
changes the width of the very next output field and then immediately reverts to the
default. Listing 17.12 illustrates its use.
ANALYSIS