Formatting Output with stream Functions

  1. The layout of a program's output is called the format of the output.

  2. The following formatting instructions were used to format output to the screen:

    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    These instructions are actually member functions of cout. The output file stream class ofstream has the same member functions as cout, and these functions can be used to format the data output to files. For example you may use

    outs.setf(ios::fixed);
    outs.setf(ios::showpoint);
    outs.precision(2);

    if outs has been declared an output file stream and it has been connected to an external file.

  3. Member function precision(n) causes any number with a decimal point that is output to a file stream to be written with 2 significant figures (or with 2 decimal places depending on your compiler).

  4. Member function setf sets a flag. A flag is simply an instruction to do something in one of two possible ways. The flag ios::fixed causes the stream to output numbers of type double in fixed point notation rather than scientific notation (which normally is used automatically if the number happens to be either very larger or very small).

  5. The flag ios::showpoint tells the stream to always include a decimal point even if the output number happens to have a zero fractional part.

  6. Once a flag is set, it is in effect until the flag is unset using the unsetf member function, or when the flag is set to something else. For example you may use ins.unsetf(ios::fixed) to unset the flag ios::fixed, or use ins.setf(ios::scientific) to set the flag to use scientific notation.

  7. Another useful formatting function is "width", which tell the stream the number of spaces to use to output the next item. For example, if the integers num1, num2 and num3 have values 1, 12 and 123, respectively, then the code

    cout << "Number1";
    cout.width(5);
    cout << num1 << endl;
    cout << "Number2";
    cout.width(5);
    cout << num2 << endl;
    cout << "Number3";
    cout.width(5);
    cout << num3 << endl;

    will produce the following output on the screen:

    Number1    1
    Number2   12
    Number3  123
    
    The width function affect only the next item that is output. This is why we needed to call width three times in the above example.

    The entire item is always output, no matter what argument is given to width. If the output requires more space than you specified in the argument to width, then as much additional space as is needed will be used.