C++ Basic Output Bob Walton, 7/16/96 Values can be output in C++ by statements such as: int x = ...; foo y = ...; cout << "x = " << x << ", y = " << y << endl; In order to make the above work, one must: #include The outputting is done by the operator <<. `cout' is the standard output stream, and is of type `ostream'. If struct foo { int value; }; is the definition of `foo', then a possible definition for the << operator to output a `foo' value is: ostream & operator >> ( ostream & s, foo const & v ) { return s << "foo (" << v.i << ")"; } Here `s' is an `output stream', which might be `cout'. A representation of `v' is output to this `ostream', and the ostream is returned as the value of the << operator so calls to the << operator can be concatenated as in `cout << x << y'. Note that the ostream is passed by reference (&). The standard data types print what one would expect. Number types print without any surrounding spaces if output by << to an output stream that has not been specially modified to do otherwise. Such modifications can be made by `output manipulators', which will not be described here. There is a special output manipulator to flush an output stream so its contents are sent to the output device, and not stuck in internal buffers. This is the `flush' output manipulator, for which a typical use is: cout << "Input a number: " << flush; The `endl' manipulator may be used similarly: it outputs a new line and then does a flush. Thus lines are often ended with `<< endl'. One can end lines with "\n" or '\n' if one does not care about flushing internal buffers to the output devices. Also, reading `cin' generally causes the `cout' to be flushed before input occurs.