Implementing an Ostream Sample

Description

An ostream is used to convert values (such as int or double) into sequences of characters. Typically, these character sequences are then actually output, for example to a terminal window. But there's no requirement that an actual file or output device be used, and it's possible to send output to a string or vector of characters.

This samples illustrates how to develop your own output stream, tied to a char[] vector. The idea is to use ostream for the formatting operations (converting values to character sequences), and then specify a buffer that ostream uses to actually store the resulting characters. The buffer will be initialized with the vector specified by the user.

Concept

The sample program declares a type outbuf, derived from basic_streambuf. The constructor for outbuf initializes the buffer structure, using setbuf() and setp(). Output using << will be placed into this buffer. As a check of whether the output operations worked, the underlying buffer is itself output.

Special Notes:

See ostringstream for a variation on this idea.

Supported
Supported
Supported