cout << ExpressionOrManipulator << ExpressionOrManipulator << ... ;The C++ standard library supplies many manipulators, here are a few of them:
Category | Manipulator | Description |
---|---|---|
flow | endl |
|
Field Width | setw(n) |
|
left |
|
|
right |
|
|
Floating Point | setprecision(n) |
|
fixed |
|
|
scientific |
|
|
defaultfloat |
|
|
showpoint |
|
|
noshowpoint |
|
Now look at an example and see how those manipulators are used:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//Constant to control column width in table
const int colw = 11;
//Set precision to 3 instead of the default of 6
cout << setprecision(3);
//Align column labels left
cout << left;
//Print column labels
cout << setw(colw) << "Default" << "|"
<< setw(colw) << "Fixed" << "|"
<< setw(colw) << "Scientific" << "|"
<< setw(colw) << "+Showpoint" << "|"
<< setw(colw) << "Def. Float" << "|"
<< setw(colw) << "-Showpoint" << endl;
//Print a separator line below the labels for 6 column widths + 5 '|'
//setfill(char) prints the char specified instead of a ' ' for wide columns
cout << setfill('-') << setw(colw*6 + 5) << "" << setfill(' ') << endl;
//Align rest of table right
cout << right;
//Print row 1
float f = 3;
cout << setw(colw) << f << "|"
<< fixed << setw(colw) << f << "|"
<< scientific << setw(colw) << f << "|"
<< showpoint << setw(colw) << f << "|"
<< defaultfloat << setw(colw) << f << "|"
<< noshowpoint << setw(colw) << f << endl;
//Print row 2
f = 123456.78;
cout << setw(colw) << f << "|"
<< fixed << setw(colw) << f << "|"
<< scientific << setw(colw) << f << "|"
<< showpoint << setw(colw) << f << "|"
<< defaultfloat << setw(colw) << f << "|"
<< noshowpoint << setw(colw) << f << endl;
//Print row 3
f = .000123;
cout << setw(colw) << f << "|"
<< fixed << setw(colw) << f << "|"
<< scientific << setw(colw) << f << "|"
<< showpoint << setw(colw) << f << "|"
<< defaultfloat << setw(colw) << f << "|"
<< noshowpoint << setw(colw) << f << endl;
return 0;
}
You may run this program and compare the output with what you expected.