Manipulators

A manipulator is a function object that can be used as an operand to an input or output operator to manipulate the stream. Manipulators can send additional output to a stream, read input from a stream, set flags, and more. For example, to output a zero-padded, hexadecimal integer, you can use an ostream’s member functions or manipulators, whichever you prefer. Example 9-7 shows both ways.

Example 9-7. Manipulating an output stream to format a number
using namespace std;

// Output a value using ostream's member functions.
cout.fill('0');
cout.width(8);
cout.setf(ios_base::internal, ios_base::adjustfield);
cout.setf(ios_base::hex, ios_base::basefield);
cout << value;

// Output the same value using manipulators.
cout << setfill('0') << setw(8) << hex << internal << value;

Standard Manipulators

The standard library defines several manipulators for setting formatting flags, setting other formatting parameters, skipping whitespace, flushing output, and more. The following is a list of all the standard manipulators, grouped by header:

<ios>

Declares the manipulators that set the formatting flags: boolalpha , dec , fixed , hex , internal , left , noboolalpha , noshowbase , noshowpoint , noshowpos , noskipws , nouppercase , nounitbuf , oct , right , scientific , showbase , showpoint , showpos , skipws , uppercase , and unitbuf

<istream>

Declares the input manipulator: ws

<ostream>

Declares the output manipulators: endl , ends , and flush

<iomanip>

Declares several additional manipulators: ...

Get C++ In a Nutshell 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.