Use of the setf(), width(), and similar member functions is very convenient if the same specifications are used for a large number of inserted items. |
|
If the formatting frequently changes, it is more convenient to use a manipulator. |
|
A manipulator is an object that can be an operand to the << or >> operator, but which modifies the state of the stream, rather than actually inserting or extracting any data. |
|
For instance, the manipulators hex and dec can be used to request hexadecimal or decimal printing of integral values. |
|
Thus, the following sequence can be used to write out the value of i in decimal and the value of x[i] in hexadecimal: |
|
cout << “i = ” << dec << i << “, |
|
x[i] = ” << hex << x[i]; |
|
Other manipulators include the following: |
|
ws skips white space on input. |
|
flush flushes a stream’s buffer. |
|
endl inserts a newline character and then flushes the stream’s buffer. |
|
ends inserts an end-of-string character ( ‘\0’ ). |
|
It is possible to create user-defined manipulators in addition to the standard manipulators, but this is beyond the scope of this book. |
|
See class IOMANIP for examples of user-defined manipulators, or refer to the C++ Programming Language, Second Edition for a detailed discussion. |