Tutorial
C++
I/O Manipulators

Manipulators

A manipulator is actually nothing more than a function defined in a way that allows us to use it as if it were an object. They are called manipulators because they allow you to manipulate (or control) the formatting of input and output streams (such as files and cin, cout, and cerr). Although it is possible to write your ow manipulators, we will restrict ourselves (at least for the moment) to merely using them. In fact, you've already used a manipulator -- endl is a manipulator that inserts a newline into the output stream. (Note how the syntax cout << endl is identical to that of sending any value or object to cout).

To begin with, to be able to work with manipulators, we need a new #include-- this one is for the library iomanip:

#include <iomanip>
		
Our first example of a manipulator is setw (for set width). Unlike endl, this manipulator takes a parameter-- the width of the field to be printed. Thus setw(5) means that whatever you're about to print should take up 5 characters (columns) in the output. The setw only applies to the next item printed-- you have to use it again for any subsequent items.

Here's an example-- now neatly columned using the setw manipulator:

void columnPrint1() {
    for (int i = 0; i < 5; i++)
        cout << setw(5) << i;
    cout << endl;

    for (int i = 0; i < 5; i++)
        cout << setw(5) << i* 10;
    cout << endl;

    for (int i = 0; i < 5; i++)
        cout << setw(5) << i * 100;
    cout << endl;
}		
		
and here is the output:
    0    1    2    3    4
    0   10   20   30   40
    0  100  200  300  400
		
Notice how the manipulator is specified much like any other value sent to cout-- we speak of inserting both the manipulator setw as well as the value i into the stream. (Similarly, the << is called the insertion operator.)

Other manipulators