Iostream header files
|
Header File |
Description |
|
iostream.h |
Defines a hierarchy of classes for low-level (untyped character-level) IO and high-level (typed) IO. This includes the definition of the ios, istream, ostream, and iostream classes. |
|
fstream.h |
Derives a set of classes from those defined in iostream.h for file IO. This includes the definition of the ifstream, ofstream, and fstream classes. |
|
strstream.h |
Derives a set of classes from those defined in iostream.h for IO with respect to character arrays. This includes the definition of the istrstream, ostrstream, and strstream classes. |
|
iomanip.h |
Defines a set of manipulator which operate on streams to produce useful effects. |
Highest-level iostream classes.
|
Form of IO |
Input |
Output |
Input and Output |
|
Standard IO |
istream |
ostream |
iostream |
|
File IO |
ifstream |
ofstream |
fstream |
|
Array of char IO |
istrstream |
ostrstream |
strstream |
Predefined streams.
|
Stream |
Type |
Buffered |
Description |
|
cin |
istream |
Yes |
Connected to standard input (e.g., the keyboard) |
|
cout |
ostream |
Yes |
Connected to standard output (e.g., the monitor) |
|
clog |
ostream |
Yes |
Connected to standard error (e.g., the monitor) |
|
cerr |
ostream |
No |
Connected to standard error (e.g., the monitor) |
A stream may be used for input, output, or both. The act of reading data from an input stream is called extraction. It is performed using the >> operator (called the extraction operator) or an iostream member function. Similarly, the act of writing data to an output stream is called insertion, and is performed using the << operator (called the insertion operator) or an iostream member function. We therefore speak of ‘extracting data from an input stream’ and ‘inserting data into an output stream’.
· A put pointer points to the position of the next character to be deposited into the sequence as a result of an insertion.
· A get pointer points to the position of the next character to be fetched from the sequence as a result of an extraction.
For example, ostream only has a put pointer, istream only has a get pointer, and iostream has both pointers.When a stream is created, a streambuf is associated with it. Therefore, the stream classes provide constructors which take a streambuf* argument. All stream classes overload the insertion and extraction operators for use with a streambuf* operand. The insertion or extraction of a streambuf causes the entire stream represented by it to be copied. ¨
This section looks at the ostream member functions.
The put member function provides a simple method of inserting a single character into an output stream. For example, assuming that os is an ostream object,
os.put('a');
inserts 'a' into os.
Similarly, write inserts a string of characters into an output stream. For example,
os.write(str, 10);
inserts the first 10 characters from str into os.
An output stream can be flushed by invoking its flush member function. Flushing causes any buffered data to be immediately sent to output:
os.flush(); // flushes the os buffer
The position of an output stream put pointer can be queried using tellp and adjusted using seekp. For example,
os.seekp(os.tellp() + 10);
moves the put pointer 10 characters forward. An optional second argument to seekp enables the position to be specified relatively rather than absolutely. For example, the above is equivalent to:
os.seekp(10, ios::cur);
The second argument may be one of:
· ios::beg for positions relative to the beginning of the stream,
· ios::cur for positions relative to the current put pointer position, or
· ios::end for positions relative to the end of the stream.
These are defined as a public enumeration in the ios class.
All output functions with an ostream& return type, return the stream for which they are invoked. Multiple calls to such functions can be concatenated (i.e., combined into one statement). For example,
os.put('a').put('b');
is valid and is equivalent to:
os.put('a');
os.put('b');
Member functions of ostream.
|
ostream (streambuf*); The constructor associates a streambuf (or its derivation) with the class to provide an output stream. |
|
ostream& put (char); Inserts a character into the stream. |
|
ostream& write (const signed char*, int n); ostream& write (const unsigned char*, int n); Inserts n signed or unsigned characters into the stream. |
|
ostream& flush (); Flushes the stream. |
|
long tellp (); Returns the current stream put pointer position. |
|
ostream& seekp (long, seek_dir = ios::beg); Moves the put pointer to a character position in the stream relative to the beginning, the current, or the end position: enum seek_dir {beg, cur, end}; |
Stream Input with istream
This section looks at the istream member functions.
The get member function provides a simple method of extracting a single character from an input stream. For example, assuming that is is an istream object,
int ch = is.get();
extracts and returns the character denoted by the get pointer of is, and advances the get pointer. A variation of get, called peek, does the same but does not advance the get pointer. In other words, it allows you to examine the next input character without extracting it. The effect of a call to get can be canceled by calling putback which deposits the extracted character back into the stream:
is.putback(ch);
The return type of get and peek is an int (not char). This is because the end-of-file character (EOF) is usually given the value -1.
The behavior of get is different from the extraction operator in that the former does not skip blanks. For example, an input line consisting of
x y
(i.e., 'x', space, 'y', newline) would be extracted by four calls to get. the same line would be extracted by two applications of >>.
Other variations of get are also provided.
The read member function extracts a string of characters from an input stream. For example,
char buf[64];
is.read(buf, 64);
extracts up to 64 characters from is and deposits them into buf. Of course, if EOF is encountered in the process, less characters will be extracted. The actual number of characters extracted is obtained by calling gcount.
A variation of read, called getline, allows extraction of characters until a user-specified delimiter is encountered. For example,
is.getline(buf, 64, '\t');
is similar to the above call to read but stops the extraction if a tab character is encountered. The delimiter, although extracted if encountered within the specified number of characters, is not deposited into buf.
Input characters can be skipped by calling ignore. For example,
is.ignore(10, '\n');
extracts and discards up to 10 characters but stops if a newline character is encountered. The delimiters itself is also extracted and discarded.
The position of an input stream get pointer can be queried using tellg and adjusted using seekg. For example,
is.seekp(is.tellg() - 10);
moves the get pointer 10 characters backward. An optional second argument to seekg enables the position to be specified relatively rather than absolutely. For example, the above is equivalent to:
is.seekg(-10, ios::cur);
As with seekp, the second argument may be one of ios::beg, ios::cur, or ios::end.
All input functions with an istream& return type, return the stream for which they are invoked. Multiple calls to such functions can therefore be concatenated. For example,
is.get(ch1).get(ch2);
is valid and is equivalent to:
is.get(ch1);
is.get(ch2);
The iostream class is derived from the istream and ostream classes and inherits their public members as its own public members:
class iostream : public istream, public ostream {
//...
};
Member functions of istream.
|
istream (streambuf*) The constructor associates a streambuf (or its derivation) with the class to provide an input stream. |
|
int get (); istream& get (signed char&); istream& get (unsigned char&); istream& get (streambuf&, char = '\n'); The first version extracts the next character (including EOF). The second and third versions are similar but instead deposit the character into their parameter. The last version extracts and deposit characters into the given streambuf until the delimiter denoted by its last parameter is encountered. |
|
int peek (); Returns the next input character without extracting it. |
|
istream& putback (char); Pushes an extracted character back into the stream. |
|
istream& read (signed char*, int n); istream& read (unsigned char*, int n); Extracts up to n characters into the given array, but stops if EOF is encountered. |
|
istream& getline (signed char*, int n, char = '\n'); istream& getline (unsigned char*, int n, char = '\n'); Extracts at most n-1 characters, or until the delimiter denoted by the last parameter or EOF is encountered, and deposit them into the given array, which is always null-terminated. The delimiter, if encountered and extracted, is not deposited into the array. |
|
int gcount (); Returns the number of characters last extracted as a result of calling read or getline. |
|
istream& ignore (int n = 1, int = EOF); Skips up to n characters, but extracts and stops if the delimiter denoted by the last parameter is encountered. |
|
long tellg (); Returns the current stream get pointer position. |
|
istream& seekg (long, seek_dir = ios::cur); Moves the get pointer to a character position in the stream relative to the beginning, the current, or the end position: enum seek_dir {beg, cur, end}; |
Using the ios Class
Ios provides capabilities common to both input and output streams. It uses a streambuf for buffering of data and maintains operational information on the state of the streambuf (i.e., IO errors). It also keeps formatting information for the use of its client classes (e.g., istream and ostream).
The io_state values are used for the state data member which is a bit vector of IO error flags. The formatting flags are used for the x_flags data member (a bit vector). The open_mode values are bit flags for specifying the opening mode of a stream. The seek_dir values specify the seek direction for seekp and seekg.
Useful public enumerations in ios.
|
enum io_state: |
Provides status flags (for ios::state). |
|
ios::goodbit |
When state is set to this value, it means that all is ok. |
|
ios::eofbit |
End-of-file has been reached. |
|
ios::badbit |
An invalid operation has been attempted. |
|
ios::failbit |
The last IO operation attempted has failed. |
|
ios::hardfail |
An unrecoverable error has taken place. |
|
Anonymous enum: |
Provides formatting flags. |
|
ios::left |
Left-adjust the output. |
|
ios::right |
Right-adjust the output. |
|
ios::internal |
Output padding indicator. |
|
ios::dec |
Convert to decimal. |
|
ios::oct |
Convert to octal. |
|
ios::hex |
Convert to hexadecimal. |
|
ios::showbase |
Show the base on output. |
|
ios::showpoint |
Show the decimal point on output. |
|
ios::uppercase |
Use upper case for hexadecimal output. |
|
ios::showpos |
Show the + symbol for positive integers. |
|
ios::fixed |
Use the floating notation for reals. |
|
ios::scientific |
Use the scientific notation for reals. |
|
ios::skipws |
Skip blanks (white spaces) on input. |
|
ios::unitbuf |
Flush all streams after insertion. |
|
enum open_mode: |
Provides values for stream opening mode. |
|
ios::in |
Stream open for input. |
|
ios::out |
Stream open for output. |
|
ios::app |
Append data to the end of the file. |
|
ios::ate |
Upon opening the stream, seek to EOF. |
|
ios::trunc |
Truncate existing file. |
|
ios::noreplace |
Open should fail if file already exists. |
|
ios::nocreate |
Open should fail if file does not already exist. |
|
ios::binary |
Binary file (as opposed to default text file). |
|
enum seek_dir: |
Provides values for relative seek. |
|
ios::beg |
Seek relative to the beginning of the stream. |
|
ios::cur |
Seek relative to the current put/get pointer position. |
|
ios::end |
Seek relative to the end of the stream. |
IO operations may result in IO errors, which can be checked for using a number of ios member functions. For example, good returns nonzero if no error has occurred:
if (s.good())
// all is ok...
where s is an iostream. Similarly, bad returns nonzero if an invalid IO operation has been attempted:
if (s.bad())
// invalid IO operation...
and fail returns true if the last attempted IO operation has failed (or if bad() is true):
if (s.fail())
// la