Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Output Stream

Formatting the Output


Video Summary: https://youtu.be/omCW2Ou8ghE


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 a few of them:

Category Manipulator Description
flow endl
  • Inserts an end-of-line character: the next output will be at the start of the next line.
Field Width setw(n)
  • Controls how many character positions the next data item should occupy when it is output.
  • Not sticky: Only one item is affected.
  • n: an integer that represents the field width (number of character positions).
  • The output is right justified by default.
left
  • Sticky: all subsequent setw(n) will align left until right is used
right
  • Sticky: all subsequent setw(n) will align right until left is used
Floating Point setprecision(n)
  • Sticky: set a new precision - exact meaning of precision varies
  • By default this controls the maximum number of digits to use when printing floating point numbers.
  • If the number is too large or small for the precision to include the decimal, then output will switch to scientific notation.
  • Default precision is 6.
fixed
  • Sticky: switch floating point output to use fixed point notation,
  • setprecision(n) now controls the number of places that appear after the decimal.
scientific
  • Sticky: switch floating point output to in scientific notation,
  • setprecision(n) controls the maximum number of significant figures.
showpoint
  • Sticky: Forces the printing of all significant figures as indicated by setprecision(n), even if they are trailing zeros.

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: