Formatting Output in C++

Output in C++ can be fairly simple.

We have cout, which is "standard output", actually a predefined instance of the ostream class.

To write output to cout, we use the insertion operator <<. The name refers to "inserting values into the output stream".

If we have variables such as

     int M = 13;
     float G = 5.91;
     char X = 'P';

we can simply write

     cout << M;

and the value of M is printed. We could string several of these together and include strings:

     cout << "M = " << M << " and " G = " << G;

In each case, the value of the string or variable is printed using a default format. What if we want to change this and print values in other formats?

C++ provides a family of format specifiers we can use.


A few specifiers useful in general


Formats for number in general


Formats for integers


Formats for floating-point numbers

Note about fixed vs. scientific: The default is neither of these. If you don't indicate your choice, C++ will choose a format for you.


Formats for bool values


What is needed to make use of these?

The specifiers which are simply flags, such as hex, oct, dec, left, right, etc. are in the iostream library.

The specifiers which are functions, that is, which take arguments, such as setw, setprecision, setfill, etc. are in the iomanip library.

This is why we commonly have two #include statements for these libraries in our programs:

     #include <iostream>
     #include <iomanip>

For each of these names, we wil also need a using statement, as in

     using std::cout;


Alternate notation

Although the specifiers listed above are normally used with cout, it is also possible to set any of these with actual function calls, as in:

    cout.setf(ios_base::oct, ios_base::basefield);

     cout.setf(ios_base::scientific, ios_base::floatfield);

     cout.precision(4);

     cout.width(7);

     cout.setf(ios_base::left, ios_base::adjustfield);

     cout.fill('?');

     cout.flush();

Here: