next up previous
Next: Formatting with ANSI C Up: The ostream, istream, ofstream Previous: istream methods

ostream methods

The identifiers cout and cerr are instances of the ostream class. They map to the Unix standard output and standard error devices, respectively. (The less used clog is also an instance of this class.) The format of numbers written to these devices can be controlled through the methods and constants of this class.

In the following example we read a table of $x$ and $y$ values and write it out with a fixed decimal point, with four digits past the decimal, and with right-justification in a column of width seven characters for each value.

#include <iostream>
   double x,y;

   // Set 4 digits past decimal
   // Specify right-justified numbers in fixed format (xxx.xxxx)
   // Note: Multiple options are added and then passed to flags.
   cout.flags(ios::right | ios::fixed);
   // Write a column header
   cout << "\n  x     y\n";
   cout << "--------------\n";
     cin >> x >> y;
     if(;  // Stop on end-of-file or format error
     // Specify 7 character field width.  Must be done for each value.
     cout << x;
     cout << y << "\n";

The precision(int) method sets the number of digits past the decimal point for fixed decimal format or the total number of digits for scientific notation. It remains in force until called again.

The flags(...) method determines the justification and notation. The constants are in the ios namespace. Use the vertical bar | (bitwise logical ``or'') to combine options. The obvious choices for justification are left and right. The common choices for notation are fixed for fixed decimal point and scientific for scientific notation. This setting remains in force until you call the flags method again with new values.

Here is a longer list of ios constants:

ios constant purpose
right right-justify
left left-justify
fixed fixed-point notation
scientific scientific notation
floatfield either fixed or scientific
hex hexadecimal
Fixed point notation displays the number without using a power of ten. Scientific notation displays the power of ten after the letter e. The default value is floatfield, meaning whichever fits better. To combine compatible choices, simply add them, as we have done.

The width(int) method must be called for each value. It determines the number of characters allocated to the number. The value is really a lower bound. If the number does not fit the requested space, the width request is ignored.

next up previous
Next: Formatting with ANSI C Up: The ostream, istream, ofstream Previous: istream methods
Carleton DeTar 2008-11-10