next up previous
Next: Formatting with ANSI C Up: Formatting output Previous: Formatting output

Formatting under ostream

To some extent you can control the alignment of numbers with the special characters \n for end of line and \t for tab. But better control of formatting in cout is accomplished through its methods and the constants of a special ios class, which you get when you include iostream.

Here is an example of its use in printing a table of $x,y$ values in two columns. Each of the numbers is right-justified in a field of width seven spaces and is displayed with a decimal point and four digits past the decimal.

#include <iostream.h>
  ...
  double x[10], y[10];
  cout.precision(4);                 // Set 4 digits past the decimal
  cout.flags(ios::right+ios::fixed); // Fixed point, right justified
  ...

  // Write column header
  cout << "\n  x     y\n";
  cout << "--------------\n";
  for( i = 0; i < 10; i++){
      cout.width(7);                 // Set width for x[i]
      cout << x[i];
      cout.width(7);                 // Set width for y[i]
      cout << y[i] << "\n";
    }
  ...
Here we use the ostream methods precision, flags, and width to set the format. The method precision takes an integer for its argument, specifying the number of digits past the decimal point. The method flags takes a combination of constants defined in the ios class. Here are some of them:
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 without 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.

Of course, these methods can be called as many times as needed to vary the output format. The methods precision and flags set values that apply to all subsequent output unless they are invoked with new values. But the width method applies only to the next cout value, after which it is reset to the default value. That is why we had to call it before writing x[i] and again, y[i].


next up previous
Next: Formatting with ANSI C Up: Formatting output Previous: Formatting output
Carleton DeTar 2007-10-31