Streams and Files - 10.1 Lining Up Text Output Problem
(Page 2 of 4 )
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 <ostream>, 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 <iostream>
#include <iomanip>
#include <string>
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 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.
Next: Tables for Text Manipulation >>
More C++ Articles
More By O'Reilly Media
|
This article is excerpted from chapter 10 of the C++ Cookbook, written by Ryan Stephens, Christopher Diggins, Jonathan Turkanis and Jeff Cogswell (O'Reilly; ISBN: 0596007612). Buy this book now.
|
|