Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page