10.1. 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 <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 ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.