ios_base::fmtflags flags = cout.flags(); string first, last, citystate; int width = 20;
first = "Richard"; last = "Stevens"; citystate = "Tucson, AZ";
cout << left // Left-justify in each field << setw(width) << first // Then, repeatedly set the width << setw(width) << last // and write some data << setw(width) << citystate << endl;
The output looks like this:
Richard Stevens Tucson, AZ
A manipulator is a function that operates on a stream. Manipulators are applied to a stream with operator<<. The stream's format (input or output) is controlled by a set of flags and settings on the ultimate base stream class, ios_base. Manipulators exist to provide convenient shorthand for adjusting these flags and settings without having to explicitly set them via setf or flags, which is cumbersome to write and ugly to read. The best way to format stream output is to use manipulators.
Example 10-1 uses two manipulators to line up text output into columns. The manipulator setw sets the field width, and left left-justifies the value within that field (the counterpart to left is, not surprisingly, right). A "field" is just another way of saying that you want the output to be padded on one side or the other to make sure that the value you write is the only thing printed in that field. If, as in Example 10-1, you left-justify a value, then set the field width, the next thing you write to the stream will begin with the first character in the field. If the data you send to the stream is not wide enough to span the entire field width, the right side of it will be padded with the streams fill character, which is, by default, a single space. You can change the fill character with the setfill manipulator, like this:
myostr << setfill('.') << "foo";
If the value you put in the field is larger than the field width, the entire value is printed and no padding is added.