< previous page page_109 next page >

Page 109
Manipulators
For some time now, we have been using the endl manipulator to terminate an output line. In C++ a manipulator is a rather curious thing that behaves like a function but travels in the disguise of a data object. Like a function, a manipulator causes some action to occur. But like a data object, a manipulator can appear in the midst of a series of insertion operations:
cout << someInt << endl << someFloat;
(Manipulators are used only in input and output statements.)
Here's a revised syntax template for the output statement, showing that not only expressions and strings but also manipulators are allowed:
0109-01.gif
The C++ standard library supplies many manipulators, but for now we look at only three of them:endl, setw, and setprecision. The endl manipulator comes "for free" when we #include the header file iostream.h: to perform I/O. The other two manipulators, setw and setprecision, require that we also #include the header file iomanip.h:
#include <iostream.h>
#include <iomanip.h>
  .
  .
  .
cout << setw(5) << someInt;
The manipulator setw-meaning ''set width"-lets us control how many columns the next data item should occupy when it is output, (setw is only for formatting numbers and strings, not char data.) The parameter to setw is an integer expression called the fieldwidth specification; the desired number of columns is called the field. The next data item to be output is printed right-justified (filled with blanks on the left to fill up the field).
Let's look at an example:
ans = 33   Integer
num = 7132 Integer

 
< previous page page_109 next page >