Formatting C++ Output
We have already seen how to format floating point output with the printf() function. We can also format them with cout (although the style is a bit cryptic):
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
We can format output in other ways also (see pages 317-322)
Scientific notation: cout.setf(ios::scientific);
Specific width: cout.width(n); where n is the field width in number of characters
Right (or left) justified output: cout.setf(ios::right); (or cout.setf(ios::left);)
Some of these formatting commands are so useful (and used so often) that they have more convenient forms called IO Manipulators.
Specific width: Use setw(n) in place of cout.width(n);
Example: cout << ":" << setw(5) << x << ":" << endl;
Specific precision: Use setprecision(n) in place of cout.precision(n);
Example: cout << setprecision(2) << y << endl;
To use IO Manipulators, you need to include <iomanip> in the same way as <iostream>
There are other IO Manipulators, you can read about them here.