C++ Stream I/O
 

Streams:

Stream Output

Stream Input

Additional code examples illustrating:
- ignore
- putback
- peek
 

Stream State Bits

There are several bit flags in every stream object There are member functions that are used to return the values of the bit flags.  The corresponding functions return true when the bit is set, and false when the bit is not set (i.e. is 0). Here is an example from Deitel that illustrates the return values from these functions:  fig12_22.cpp

Here is a more practical example that illustrates how to check the fail bit to recover from an invalid type being entered on an input stream:

I/O Formatting with <iomanip>


Stream manipulators are various symbols or functions in the <iomanip> library that are used in conjunction with the insertion operator for output streams (or the extraction operator for input streams).  Most of them are used primarily for formatting output.  An example of a stream manipulator is the hex manipulator, which causes integers to be printed out in hexadecimal format.  Sample usage would look like this:

int x = 12345;
cout << hex << x;

Some stream manipulators are equivalent to corresponding member functions (which are called through the usual dot-operator).  Most stream manipulators set formatting for the entire stream -- meaning that the set format will apply until another manipulator changes it.  For example, the hex manipulator will cause all successive integer outputs to be in hex format until the format is reset to something different.
 

Some common stream manipulators

Code Examples (from Deitel):

Important Note

Some of these features of <iomanip>, especially some of the stream manipulators, constitute a newer style of formatting and only work on newer compilers. In older style libraries, some of the format flags were set via the use of special member functions like setf, unsetf, and flags -- or with parameterized stream manipulators like setiosflags() and resetiosflags.

Example: The newer vs. older style for a few format flags.

 cout << left;  // newer style
 cout << setiosflags(ios::left);  // older style

 cout << fixed;  // newer style
 cout << setiosflags(ios::fixed);  //older style

The 3rd edition of Deitel contains examples that are in the older style. You can find these here.

If the newer style stream manipulators don't work with a certain compiler, then you will probably have to use the older ones

Some affected manipulators:

 left
 right
 internal
 showbase
 skipws
 showpoint
 uppercase
 showpos
 scientific
 fixed