Formatting the Output

To format a program's output means to control how it appears visually on the screen or on a printer. We use the special ostream variable cout together with the insertion operator << to accomplish this. Here is what an output statement looks like.
cout << ExpressionOrManipulator <<  ExpressionOrManipulator <<  ... ;
The C++ standard library supplies many manipulators, here are five of them:
Manipulator	Description


endl Inserts an end-of-line character and forces the next output to begin on the next line.

setw(n) Controls how many character positions the next data item should occupy when it is output. setw is only for formatting numbers and strings. Its argument is the fieldwith (number of character positions). The output is right justified.

fixed Forces all subsequent floating-point output to appear in decimal form rather than scientific notation.

showpoint Forces decimal points to be displayed in subsequent floating-point output and even in whole number output.

setprecision(n) Controls the number of positions for fractional digits.
In this table, the manipulators without arguments (such as endl, fixed, showpoint) are available through the header file iostream. Those with argument (such as setw(n), setprecision(n)) require the header file iomanip.

Now look at an example and see how those manipulators are used:


// Program Format demonstrates the use of fieldwidth;
// specifications.

#include <iostream>
#include <iomanip>
using namespace std;

const int INT_NUMBER = 1066;        //define an int constant
const float FLT_NUMBER = 3.14159;   //define a float constant

int main ()
{
    float fltValue;	//declare a float type variable
    int   intValue;	//declare an int type variable

    //to set all printout in decimal format 
    //with decimal points appearing
    cout << fixed << showpoint;	    

    intValue = INT_NUMBER + FLT_NUMBER;		//Type coercing
    fltValue = float(INT_NUMBER) + FLT_NUMBER;	//Type casting
    cout << INT_NUMBER  << endl;
    cout << intValue  << endl;

    //reserve 10 character positions for intValue
    cout << setw(10)  << intValue; 
    cout << setw(10)  << intValue  << intValue /10  << endl;

    //reserve 10 character positions for fltValue
    cout << setw(10)  << fltValue  << endl;

    //set precision to 4 decimal positions
    cout << setprecision(4)  << fltValue  << endl;

    //reserve 10 character positions for fltValue
    //and reset precision to 3 decimal positions
    cout << setw(10)  << setprecision(3)  << fltValue << endl;
    cout << fltValue << endl;

    //print intValue takeing as many character positions as needed, 
    //and then reserve 3 character positions for intValue
    //and then reserve 7 character positions for intValue
    cout << intValue  << setw(3)  << intValue  << setw(7)
	 << intValue << endl;

    return 0;
}
You may run this program and compare the output with what you expected.



Copyright: Department of Computer Science, University of Regina.