Copyright (C) 1993 Free Software Foundation, Inc.

The author of this software is David M. Gay.

Copyright (c) 1991 by AT&T.

Permission to use, copy, modify, and distribute this software for any purpose without fee is hereby granted, provided that this entire notice is included in all copies of any software which is or includes a copy or modification of this software and in all copies of the supporting documentation for such software.

THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided also that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.


3 Stream Classes

The previous chapter referred in passing to the classes ostream and istream, for output and input respectively. These classes share certain properties, captured in their base class ios.

3.1 Shared properties: class ios

The base class ios provides methods to test and manage the state of input or output streams.

ios delegates the job of actually reading and writing bytes to the abstract class streambuf, that is designed to provide buffered streams. See Using the streambuf Layer, for information on the facilities available at the streambuf level.

Constructor: ios::ios ([streambuf* sb [, ostream* tie])
The ios constructor by default initializes a new ios and if  supplied with a streambuf>sb to associate with it, sets the state good in the new ios object. It also sets the default properties of the new object.

An optional second argument tie can be supplied to the constructor: if present, it is an initial value for ios::tie, to associate the new ios object with another stream.

Destructor: ios::~ios ()
The ios destructor is virtual, permitting application-specific behavior when a stream is closed--typically, the destructor frees any storage associated with the stream and releases any other associated objects.

3.1.1 Checking the state of a stream

Use this collection of methods to test for (or signal) errors and other exceptional conditions of streams:

Method: ios::operator void* () const
Perform a quick check on the state of the most recent operation on a stream by examining a pointer to the stream itself. The pointer is arbitrary except for its truth value; it is true if no failures have occurred (ios::fail is not true). For example, the user might ask for input on cin only if all prior output operations succeeded:

if (cout)
{
  // Everything OK so far
  cin >> new_value;
  ...
}

Method: ios::operator ! () const
In some cases it is more convenient to check whether something has failed. The operator ! returns true if ios::fail is true (an operation has failed). For example, the following code snippet shows an error message issued if input failed:

if (!cin)
{
  // Oops
  cerr << "Eh?\n";
}

Method: iostate ios::rdstate () const
Returns the state flags for this stream. The value is from the enumeration iostate. It can be tested for any combination of the following:

goodbit
There are no indications of exceptional states on this stream.
eofbit
End of file.
failbit
An operation has failed on this stream; this usually indicates bad format of input.
badbit
The stream is unusable.

Method: void ios::setstate (iostate state)
Sets the state flag for this stream to state, in addition to, any state flags already set. Synonym (for upward compatibility): ios::set.

See ios::clear to set the stream state without regard to existing state flags. See ios::good, ios::eof, ios::fail, and ios::bad, to test the state.

Method: int ios::good () const
Tests the state flags associated with this stream; true if no error indicators are set.

Method: int ios::bad () const
Tests if a stream is marked as unusable. (if ios::badbit is set).

Method: int ios::eof () const
True if end of file was reached on this stream. (If ios::eofbit is set).

Method: int ios::fail () const
Tests for any kind of failure on this stream: either some operation failed, or the stream is marked as bad. (If either ios::failbit or ios::badbit is set).

Method: void ios::clear (iostate state)
Sets the state indication for this stream to the argument state. If called with no argument, the state is set to good (no errors pending).

See ios::good, ios::eof, ios::fail, and ios::bad, to test the state. See ios::set or ios::setstate for an alternative way to set the state.

3.1.2 Choices in formatting

These methods control (or report on) settings for some details of controlling streams, primarily to do with formatting output:

Method: char ios::fill () const
Reports on the padding character in use.

Method: char ios::fill (char padding)
Sets the padding character. The manipulator setfill can also be used. See Changing stream properties using manipulators.

Default: blank.

Method: int ios::precision () const
Reports the number of significant digits currently in use for output of floating point numbers.

Default: 6.

Method: int ios::precision (int signif)
Sets the number of significant digits (for input and output numeric conversions) to signif.

The manipulator setprecision can also be used for this purpose. See Changing stream properties using manipulators.

Method: int ios::width () const
Reports the current output field width setting (the number of characters to write on the next `<<' output operation).

Default: 0, which means; use as many characters as necessary.

Method: int ios::width (int num)
Sets the input field width setting to num. Returns the previous value for this stream.

This value resets to zero (the default) every time `<<' is used; it is essentially an additional implicit argument to that operator. The manipulator setw can also be used for this purpose. See Changing stream properties using manipulators.

Method: fmtflags ios::flags () const
Returns the current value of the complete collection of flags controlling the format state. These are the flags and their meanings when set:

ios::dec
ios::oct
ios::hex
What numeric base to use in converting integers from internal to display representation, or vice versa: decimal, octal, or hexadecimal, respectively. The base can be changed using the manipulator setbase, or any of the manipulators dec, oct, or hex; see Changing stream properties using manipulators.On input, if none of these flags is set, read numeric constants according to the prefix: decimal if no prefix (or a `.' suffix), octal if a `0' prefix is present, hexadecimal if a `0x' prefix is present. Default: dec.
ios::fixed
Avoid scientific notation, and always show a fixed number of digits after the decimal point, according to the output precision in effect. Use ios::precision to set precision.
ios::left
ios::right
ios::internal
Where output is to appear in a fixed-width field; left-justified, right-justified, or with padding in the middle (e.g. between a numeric sign and the associated value), respectively.
ios::scientific
Use scientific (exponential) notation to display numbers.
ios::showbase
Displays the conventional prefix as a visual indicator of the conversion base: no prefix for decimal, `0' for octal, `0x' for hexadecimal.
ios::showpoint
Displays a decimal point and trailing zeros after it to fill out numeric fields, even when redundant.
ios::showpos
Displays a positive sign on display of positive numbers.
ios::skipws
Skips white space. (On by default).
ios::stdio
Flush the C stdio streams stdout and stderr after each output operation (for programs that mix C and C++ output conventions).
ios::unitbuf
Flush after each output operation.
ios::uppercase
Use upper-case characters for the non-numeral elements in numeric displays; for instance, `0X7A' rather than `0x7a', or `3.14E+09' rather than `3.14e+09'.

Method: fmtflags ios::flags (fmtflags value)
Sets value as the complete collection of flags controlling the format state. The flag values are described under `ios::flags ()'.

Use ios::setf or ios::unsetf to change one property at a time.

Method: fmtflags ios::setf (fmtflags flag)
Sets one particular flag (of those described for `ios::flags ()'; return the complete collection of flags previously in effect. (Use ios::unsetf to cancel.)

Method: fmtflags ios::setf (fmtflags flag, fmtflags mask)
Clears the flag values indicated by mask, then sets any of them that are also in flag. (Flag values are described for `ios::flags ()'.) Returns the complete collection of flags previously in effect. (See ios::unsetf for another way of clearing flags.)

Method: fmtflags ios::unsetf (fmtflags flag)
Make certain flag (a combination of flag values described for `ios::flags ()') is not set for this stream; converse of ios::setf. Returns the old values of those flags.

3.1.3 Changing stream properties using manipulators

For convenience, manipulators provide a way to change certain properties of streams, or otherwise affect them, in the middle of expressions involving `<<' or `>>'. For example:

cout << "|" << setfill('*') << setw(5) << 234 << "|";

to produce `|**234|' as output.

Manipulator: ws
Skips whitespace.

Manipulator: flush
Flushes an output stream. For example, `cout << ... <<flush;' has the same effect as `cout << ...; cout.flush();'.

Manipulator: endl
Writes an end of line character `\n', then flushes the output stream.

Manipulator: ends
Writes the string terminator character (`\0').

Manipulator: setprecision (int signif)
The value of ios::precision can be changed in `<<'< `setprecision(signif)'; for example:

cout << setprecision(2) << 4.567;

prints `4.6'. Requires `#include <iomanip.h>'.

Manipulator: setw (int n)
The value of ios::width can be changed in `<<' expressions with the manipulator `setw(n)'; for example,

cout << setw(5) << 234;

prints ` 234' with two leading blanks. Requires `#include <iomanip.h>'.

Manipulator: setbase (int base)
Where base is one of 10 (decimal), 8 (octal), or 16 (hexadecimal), change the base value for numeric representations. Requires `#include <iomanip.h>'.

Manipulator: dec
Selects decimal base; equivalent to `setbase(10)'.

Manipulator: hex
Selects hexadecimal base; equivalent to `setbase(16)'.

Manipulator: oct
Selects octal base; equivalent to `setbase(8)'.

Manipulator: setfill (char padding)
Sets the padding character, in the same way as ios::fill. Requires `#include <iomanip.h>'.

3.1.4 Extended data fields

A related collection of methods that allow  to extend this collection of flags and parameters for the user's own applications, without risk of conflict between them:

Method: static fmtflags ios::bitalloc ()
Reserves a bit (the single bit on in the result) to use as a flag. Using bitalloc guards against conflict between two packages that use ios objects for different purposes.

This method is available for upward compatibility, but is not in the ANSI working paper. The number of bits available is limited; a return value of 0 means no bit is available.

Method: static int ios::xalloc ()
Reserves space for a long integer or pointer parameter. The result is a unique nonnegative integer. It can be used as an index to ios::iword or ios::pword. Use xalloc to arrange for arbitrary special-purpose data in ios objects, without risk of conflict between packages designed for different purposes.

Method: long& ios::iword (int index)
Returns a reference to arbitrary data, of long integer type, stored in an ios instance. index, conventionally returned from ios::xalloc, identifies the particular data needed.

Method: long ios::iword (int index) const
Returns the actual value of a long integer stored in an ios.

Method: void*& ios::pword (int index)
Returns a reference to an arbitrary pointer, stored in an ios instance. index, originally returned from ios::xalloc, identifies the particular pointer needed.

Method: void* ios::pword (int index) const
Returns the actual value of a pointer stored in an ios.

3.1.5 Synchronizing related streams

Use these methods to synchronize related streams with one another:

Method: ostream* ios::tie () const
Reports on what output stream, if any, is to be flushed before accessing this one. A pointer value of 0 means no stream is tied.

Method: ostream* ios::tie (ostream* assoc)
Declares that output stream assoc must be flushed before accessing this stream.

Method: int ios::sync_with_stdio ([int switch])
Unless iostreams and C stdio are designed to work together, choose between efficient C++ streams output and output compatible with C stdio. Use `ios::sync_with_stdio()' to select C compatibility.

The argument switch can be set to  0 to choose an output that is not necessarily compatible with C stdio. The default value for switch is 1.

3.1.6 Reaching the underlying streambuf

Use this method to access the underlying object:

Method: streambuf* ios::rdbuf () const
Returns a pointer to the streambuf object that underlies this ios.

3.2 Managing output streams: class ostream

Objects of class ostream inherit the generic methods from ios, and in addition have the following methods available. Declarations for this class come from `iostream.h'.

Constructor: ostream::ostream ()
The simplest form of the constructor for an ostream simply allocates a new ios object.

Constructor: ostream::ostream (streambuf* sb [, ostream tie])
This alternative constructor requires a first argument sb of type streambuf*, to use an existing open stream for output. It also accepts an optional second argument tie, to specify a related ostream* as the initial value for ios::tie.

If the ostream is given a streambuf explicitly, using this constructor, the sb is not destroyed (or deleted or closed) when the ostream is destroyed.

3.2.1 Writing on an ostream

These methods write on an ostream (the operator << can also be used; see Operators and Default Streams).

Method: ostream& ostream::put (char c)
Writes the single character c.

Method: ostream& ostream::write (string, int length)
Write length characters of a string to this ostream, beginning at the pointer string.

string may have any of these types: char*, unsigned char*, signed char*.

Method: ostream& ostream::form (const char *format, ...)
An extension that is, similar to fprintf(file, format, ...).

format is a printf-style format control string, which is used to format the (variable number of) arguments, printing the result on this ostream. See ostream::vform for a version that uses an argument list rather than a variable number of arguments.

Method: ostream& ostream::vform (const char *format, va_list args)
An extension that is, similar to vfprintf(file, format, args).

format is a printf-style format control string, which is used to format the argument list args, printing the result on this ostream. See ostream::form for a version that uses a variable number of arguments rather than an argument list.

3.2.2 Repositioning an ostream

Control the output position (on output streams that actually support positions, typically files) with these methods:

Method: streampos ostream::tellp ()
Returns the current write position in the stream.

Method: ostream& ostream::seekp (streampos loc)
Resets the output position to loc (which is usually the result of a previous call to ostream::tellp). loc specifies an absolute position in the output stream.

Method: ostream& ostream::seekp (streamoff loc, rel)
Resets the output position to loc, relative to the beginning, end, or current output position in the stream, as indicated by rel (a value from the enumeration ios::seekdir):

beg:
Interprets loc as an absolute offset from the beginning of the file.
cur:
Interprets loc as an offset relative to the current output position.
end:
Interprets loc as an offset from the current end of the output stream.

3.2.3 Miscellaneous ostream utilities

Use these ostream methods for housekeeping:

Method: ostream& flush ()
Delivers any pending buffered output for this ostream.

Method: int ostream::opfx ()
opfx is a prefix method for operations on ostream objects; it is designed to be called before any further processing. See ostream::osfx for the converse.

opfx tests that the stream is in state good, and if so flushes any stream tied to this one.

The result is 1 when opfx succeeds; else (if the stream state is not good), the result is 0.

Method: void ostream::osfx ()
osfx is a suffix method for operations on ostream objects; it is designed to be called at the conclusion of any processing. All the ostream methods end by calling osfx. See ostream::opfx for the converse.

If the unitbuf> flag is set for this stream, osfx flushes any buffered output for it.

If the stdio flag is set for this stream, osfx flushes any output buffered for the C output streams `stdout' and `stderr'.

3.3 Managing input streams: class istream

Class istream objects are specialized for input; as for ostream, they are derived from ios, so use any of the general-purpose methods from that base class. Declarations for this class also come from `iostream.h'.

Constructor: istream::istream ()
When used without arguments, the istream constructor simply allocates a new ios object and initializes the input counter (the value reported by istream::gcount) to 0.

Constructor: istream::istream (streambuf *sb [, ostream tie])
Call the constructor with one or two arguments. The first argument sb is a streambuf*; if this pointer is supplied, the constructor uses that streambuf for input.Use the second optional argument tie to specify a related output stream as the initial value for ios::tie.

If given the istream a streambuf explicitly, using this constructor, the sb is not destroyed (or deleted or closed) when the ostream is destroyed.

3.3.1 Reading one character

Use these methods to read a single character from the input stream:

Method: int istream::get ()
Reads a single character (or EOF) from the input stream, returning it (coerced to an unsigned char) as the result.

Method: istream& istream::get (char& c)
Reads a single character from the input stream, into &c.

Method: int istream::peek ()
Returns the next available input character, but without changing the current input position.

3.3.2 Reading strings

Use these methods to read strings (for example, a line at a time) from the input stream:

Method: istream& istream::get (char* c, int len [, char delim])
Reads a string from the input stream, into the array at c.

The remaining arguments limit how much to read: up to `len-1' characters, or up to (but not including) the first occurrence in the input of a particular delimiter character delim---newline (\n) by default. (Naturally, if the stream reaches end of file first, that too will terminate reading.)

If delim was present in the input, it remains available as if unread; to discard it instead, see iostream::getline.

get: writes `\0' at the end of the string, regardless of which condition terminates the read.

Method: istream& istream::get (streambuf& sb [, char delim])
Reads characters from the input stream and copies them on the streambuf object sb. Copying ends either just before the next instance of the delimiter character delim (newline \n by default), or when either stream ends. If delim was present in the input, it remains available as if unread.

Method: istream& istream::getline (charptr, int len [, char delim])
Reads a line from the input stream, into the array at charptr. charptr may be any one of the three kinds of pointer: char*, unsigned char*, or signed char*.

The remaining arguments limit how much to read: up to (but not including) the first occurrence in the input of a line delimiter character delim---newline (\n) by default, or up to `len-1' characters (or to end of file, if that happens sooner).

If getline succeeds in reading a "full line", it also discards the trailing delimiter character from the input stream. (To preserve it as available input, see the similar form of iostream::get.)

If delim was not found before len characters or end of file, getline sets the ios::fail flag, as well as the ios::eof flag if appropriate.

getline: writes a null character at the end of the string, regardless of which condition terminates the read.

Method: istream& istream::read (pointer, int len)
Reads len bytes into the location at pointer, unless the input ends first.

pointer may be of type char*, void*, unsigned char*, or signed char*>.

If the istream ends before reading len bytes, read sets the ios::fail flag.

Method: istream& istream::gets (char **s [, char delim])
An extension used to read an arbitrarily long string from the current input position to the next instance of the delim character (newline\n by default).

To permit reading a string of arbitrary length, gets allocates whatever memory is required. Notice that the first argument s is an address to record a character pointer, rather than the pointer itself.

Method: istream& istream::scan (const char *format ...)
An extension, similar to fscanf(file, format, ...). The format is a scanf-style format control string, used to read the variables in the remainder of the argument list from the istream.

Method: istream& istream::vscan (const char *format, va_list args)
Like istream::scan, but takes a single va_list argument.

3.3.3 Repositioning an istream

Use these methods to control the current input position:

Method: streampos istream::tellg ()
Returns the current read position, to save and return to it later with istream::seekg.

Method: istream& istream::seekg (streampos p)
Resets the input pointer (if the input device permits it) to p, usually the result of an earlier call to istream::tellg.

Method: istream& istream::seekg (streamoff offset, ios::seek_dir ref)
Resets the input pointer (if the input device permits it) to offset characters from the beginning of the input, the current position, or the end of input. Specify how to interpret offset with one of these values for the second argument:

ios::beg
Interprets loc as an absolute offset from the beginning of the file.
ios::cur
Interprets loc as an offset relative to the current output position.
ios::end
Interprets loc as an offset from the current end of the output stream.

3.3.4 Miscellaneous istream utilities

Use these methods for housekeeping on istream objects:

Method: int istream::gcount ()
Reports how many characters were read from this istream in the last unformatted input operation.

Method: int istream::ipfx (int keepwhite)
Ensures that the istream object is ready for reading; check for errors and end of file and flush any tied stream. ipfx skips whitespace if  0 is specified as the keepwhite argument, and ios::skipws is set for this stream.

To avoid skipping whitespace (regardless of the skipws setting on the stream), use 1 as the argument.

Call istream::ipfx to simplify writing own methods for reading istream objects.

Method: void istream::isfx ()
A placeholder for compliance with the draft ANSI standard; this method does nothing whatever.

To write portable standard-conforming code on istream objects, call isfx after any operation that reads from an istream; if istream::ipfx has any special effects that must be cancelled when done, istream::isfx will cancel them.

Method: istream& istream::ignore ([int n] [, int delim])
Discards a number of characters pending input. The first optional argument n specifies how many characters to skip. The second optional argument delim specifies a "boundary" character: ignore returns immediately if this character appears in the input.

By default, delim is EOF; that is, if a second argument is not specified, only the count n restricts how much to ignore (while input is still available).

If the number of characters to ignore is not specified, ignore returns after discarding only one character.

Method: istream& istream::putback (char ch)
Attempts to back up one character, replacing the character backed-up over by ch. Returns EOF if this is not allowed. Putting back the most recently read character is always allowed. (This method corresponds to the C function ungetc.)

Method: istream& istream::unget ()
Attempts to back up one character.

3.4 Input and output together: class iostream

In order to use the same stream for input and output, use an object of the class iostream, which is derived from both istream and ostream.

The constructors for iostream behave just like the constructors for istream.

Constructor: iostream::iostream ()
When used without arguments, the iostream constructor simply allocates a new ios object, and initializes the input counter (the value reported by istream::gcount) to 0.

Constructor: iostream::iostream (streambuf* sb [, ostream* tie])
Call a constructor with one or two arguments. The first argument sb is a streambuf*; if this pointer is supplied, the constructor uses that streambuf for input and output.

Use the optional second argument tie (an ostream*) to specify a related output stream as the initial value for ios::tie.

As for ostream and istream,iostream simply uses the ios destructor. However, an iostream is not deleted by its destructor.

Use all the istream, ostream, and ios methods with an iostream object.