Lining Up Text Output
Problem
You need to line up your text output vertically. For example, if you are exporting tabular data, you may want it to look like this:
Jim Willcox Mesa AZ Bill Johnson San Mateo CA Robert Robertson Fort Collins CO
You will probably also want to be able to right- or left-justify the text.
Solution
Use ostream or wostream, for narrow or wide characters, defined in , and the standard stream manipulators to set the field width and justify the text. Example 10-1 shows how.
Example 10-1. Lining up text output
#include #include #include using namespace std; int main( ) { 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; cout.flags(flags); }
The output looks like this:
Richard Stevens Tucson, AZ
Discussion
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 stream's 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.
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.
Manipulator |
Description |
Sample output |
---|---|---|
leftright |
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-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. |
setfill(int c) |
Use the character c to pad fields that have remaining space. |
cout << setfill('.') << setw(10) << right << "foo" produces: .......foo |
boolalphanoboolalpha |
Display Boolean values as the current locale's representation of the words true and false, instead of 1 and 0. |
cout << boolalpha << true produces: true |
endl |
Write a newline to the stream and flush the output buffer. |
n/a |
ends |
Write a null character (` ') 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.
As with all other character-based classes in the standard library, manipulators work on streams that use narrow or wide characters. Therefore, you can use them with templates to write formatting utilities that operate on streams of any kind of character. Example 10-2 presents the class template TableFormatter , which formats data into equal-width columns and writes it to a stream.
Example 10-2. A generic class for tabular data
#include #include #include #include using namespace std; // TableFormatter formats data for output to a stream of characters // of type T. template class TableFormatter { public: TableFormatter(basic_ostream& os) : out_(os) {} ~TableFormatter( ) {out_ << flush;} template void writeTableRow(const vector& v, int width); //... private: basic_ostream& out_; }; template // refers to class template param list template // refers to mem fn template param list void TableFormatter::writeTableRow(const std::vector& v, int width) { ios_base::fmtflags flags = out_.flags( ); out_.flush( ); out_ << setprecision(2) << fixed; // Set the precision, in case // this is floating-point data for (vector::const_iterator p = v.begin( ); p != v.end( ); ++p) out_ << setw(width) << left << *p; // Set the width, justify, // and write the element out_ << endl; // Flush out_.setf(flags); // Set the flags back to normal } int main( ) { TableFormatter fmt(cout); vector vs; vs.push_back( "Sunday" ); vs.push_back( "Monday" ); vs.push_back( "Tuesday" ); fmt.writeTableRow(vs, 12); fmt.writeTableRow(vs, 12); fmt.writeTableRow(vs, 12); vector vd; vd.push_back(4.0); vd.push_back(3.0); vd.push_back(2.0); vd.push_back(1.0); fmt.writeTableRow(vd, 5); }
The output from Example 10-2 looks like this:
Sunday Monday Tuesday 4.00 3.00 2.00 1.00
See Also
Table 10-1, Recipe 10.2