The following program demonstrates the behavior of three manipulators: setw
,
left
, and right
. The program prints a '|' character at the beginning and ending
of each line, which demarcates the field width in which the data are printed and clarifies how the left
and right manipulators position output within the field.
Order is important
The manipulators must be on the left of the data that they format; imagine the arrows pointing in the direction of the data flow.
setw(20) << data
not
or
data << setw(20)setw(20) << "data = " << data
#include <iostream> #include <iomanip> using namespace std; int main() { cout << "String" << endl; cout << "|" << "Hello world" << "|" << endl; cout << "|" << setw(20) << "Hello world" << "|" << endl; cout << "|" << left << setw(20) << "Hello world" << "|" << endl; cout << "|" << right << setw(20) << "Hello world" << "|" << endl; cout << endl; cout << "Number" << endl; cout << "|" << 123.45 << "|" << endl; cout << "|" << setw(20) << 123.45 << "|" << endl; cout << "|" << left << setw(20) << 123.45 << "|" << endl; cout << "|" << right << setw(20) << 123.45 << "|" << endl; return 0; }
Output:
String |Hello world| | Hello world| |Hello world | | Hello world| Number |123.45| | 123.45| |123.45 | | 123.45|