Formatting Numbers with C++ Output Streams

Manipulators

Using the output operator with C++ streams is generally easy as pie, with the only hard part being controlling the format of the output. As you will see, this is relatively clumsy compared to C stdio's printf function, but printf is not type-safe. An output stream has a bunch of member variables that control the details of what output looks like, and these variables can be controlled by a set of member functions and special objects called manipulators

If you use manipulators that take arguments (like setprecision and setw ) you need to #include <iomanip>

Formatting Numbers with C++ Output Streams

Controlling minimum field width

You can control the minimum number of characters used to print the number by specifying the field width. Leading blanks will be included to fill up the field, but if the number doesn't fit, the extra digits will be printed regardless of the field width. The field width also affects output of strings

Example

cout << setw(4) << 12 << endl;
cout.with(4);
cout << 12 << endl;
				
Classes and Objects

Precision and the general floating-point format

You can change the maximum number of significant digits used to express a floating point number by using the precision member function or manipulator. For example

cout.precision(4);
cout << 1234.532 << 245.578 << 12345.0 << endl;
//or
cout << << setprecision(4) << 1234.532 << 245.578 << 12345.0 << endl; 
			
Classes and Objects

Precision and the fixed floating-point format

For neat output of doubles, the fixed format is most useful. (You can also select a scientific notation format.) In fixed format,the precision specifies the number of digits to the right of the decimal point, and a precision of zero means zero places to the right of the decimal point (i.e. round to the nearest unit)

cout << fixed;
cout << << setprecision(4) << 1234.532 << 245.578 << 12345.0 << endl;