IO class methods and operators
Here is the simplified class hierarchy for Input/Output in C++.
ios
/ \
/ \
/ \
/ \
istream ostream
/ \ / \
/ \ / \
/ \ / \
/ \ / \
ifstream iostream ofstream
- To use the iostream class, you must use #include <iostream>
- The iostream class has three public objects:
- cin which is attached to the standard input stream (an istream)
- cout which is attached to the standard output stream (an ostream)
- cerr which is attached to the display stream (an ostream)
- An input stream consists of a stream of data to be read, a reading
marker which points at the next character to be extracted,
and some flags to determine the state of the extraction.
- We use the extraction operator(>>) to read data from an input
stream. This operator has the following behaviours:
- It returns false if the extraction fails (we can use this
to check for the end of the file).
- It skips over all leading whitespace (spaces, tabs and new lines).
- It can be cascaded. eg cin >> a >> b >> c;
- It extracts characters one at a time and advances the reading
marker.
- The total number of characters extracted, how the extraction
terminates and how the extracted characters are used depends upon
the type of the variable being extracted. If the variable is:
- char leading whitespace is skipped and the first
non-whitespace character is extracted and stored in the variable.
The marker is left pointing at the next character. It
only fails at end of file.
- char[] leading whitespace is skipped and then
characters are extracted one at a time and stored in the array
until a whitespace character is found. The marker is
left pointing at the whitespace. It only fails at end of file.
The array must be large enough to hold the extracted characters.
- string leading whitespace is skipped and then
characters are extracted one at a time and stored in the string
until a whitespace character is found. The marker is
left pointing at the whitespace. It only fails at end of file.
- numeric leading whitespace is skipped and then
characters are extracted one at a time and stored in a
temporary string until an invalid character is found. The string
is then converted to the appropriate type. The marker
is left pointing at the invalid character. It fails if no
characters were extracted or the extracted characters could not
be converted.
- bool leading whitespace is skipped and an integer
is extracted. If the integer is 0, the value is set to false.
If it is any other value, the value is set to true. It fails if
an integer is not extracted.
- if an extractions fails, the variable is unchanged and no further
extractions are permitted until a correcting operation
is done. Note: no error message is given. Further
extractions just do nothing and the marker is not
advanced.
- An input stream object has the following methods:
- void get(char& c) extracts the next character from the input
stream and stores it in c.
- char get() extracts the next character from the input stream
and returns it.
- void ignore() extracts the next character from the input
stream but does not store it or return it. Note that this method
is used to move the marker forward one.
- void ignore(int n) extracts the next n characters or
until the marker finds an end of file whichever comes
first.
- void ignore(int n, char c) extracts the next n
characters or until the marker finds the character
c whichever comes first.
- char peek() returns the character that the marker is
pointing at but does not advance the marker.
- void putback(char c) inserts the character c into
the input stream at the marker. This function should
be used at most once after any extraction. Typically it is used
to replace a character that was just extraced.
- bool good() returns true if the last extraction was
successful, false otherwise.
- bool fail() returns true if the last extraction was
not successful and no data was lost; false otherwise.
- bool bad() returns true if the last extraction was
not successful, but data was lost; false otherwise.
- bool eof() returns true if the last extraction found
the end of file, false otherwise.
- void clear() resets the flag for the input stream to
good. Note: this is the method used to reset the
flags after an extraction has failed. After resetting, further
extractions can be done.
- void clear(int i) sets the flag for the input stream to
i. You must use one of the following constants, from the
ios class, for i:
- ios::goodbit
- ios::failbit
- ios::badbit
- ios::eofbit
- void get(char[] carray, int n) extracts characters and stores
them in carray until the marker is pointing to a
newline or n characters have been extracted, whichever
occurs first. Note that carray must be large enough for
n+1 characters in order to store the extracted characters
and the '\0' character.
- void get(char[] carray, int n, char c) extracts characters
and stores them in carray until the marker is
pointing to a character c or n characters have
been extracted, whichever occurs first. Note that carray
must be large enough for n+1 characters in order to store
the extracted characters and the '\0' character.
- void getline(char[] carray, int n, char c) same as the
previous get except that the marker is moved past the
terminating character. The terminating character is not stored.
- An output stream consists of a stream and a writing
marker which points at the next location to store a character and
some flags to determine format.
- We use the insertion operator(<<) to write data to an output
stream. This operator has the following behaviours:
- Only characters are inserted into the stream.
- It can be cascaded eg cout << a << b << c;
- It inserts characters one at a time into the stream. As each
character is inserted, the marker is moved to the next
position in the stream. The manner in which insertion happens
depends upon the type of the variable being inserted.
If the variable is:
- char the character is inserted into the stream.
- char[] each character in the array is inserted
up to the '\0' character.
- string each character in the string is inserted.
- numeric the number is converted to a temporary
string and then each character is inserted.
- bool if the value is true the character
'1' is inserted; if the value is false the character
'0' is inserted.
- The stream is not flushed, that is written, until
one of the following conditions is met:
- An istream object is used. This is useful for prompts.
- An endl is inserted. endl comes from the
iostream class and when inserted, inserts a new
line character and flushes the stream.
- A newline('\n') is inserted.
- A flush is inserted. flush comes from the
iostream class and when inserted it flushes the
stream but does not insert a newline.
- An output stream has the following methods.
- void put(char c) inserts the character c into the
output stream.
- void width(int n) causes the next insertion of a numeric
value or a char[] to be inserted in a minimum field width of
n. If more than n spaces are required to print
the value, then the width is expanded to fit. All values are
printed right justified in the field and padded with spaces as
to the specified width. If this method is not used, then the
default width is 1. After each insertion, the width is reset to
the default value. Note that width(int)does not work
with char or string values.
- long setf(long n) sets the output format flags to
n and returns the current settings. The settings remain
until changed.
The value of n must be a constant provided in the
ios class. The following are some of the possible values:
- ios::fixed floating point values will be written in
fixed decimal format
- ios::scientific floating point values will be written
in scientific notation i.e. using e notation.
- ios::left values will be left justified in the field.
- ios::right values will be right justified in the field.
- long unsetf(long n) resets the specified flag and returns
the value the flag had prior to being reset.
- void precision(int n) sets the precision for printing
floating point numbers. The precision remains in effect until
changed. The meaning of precision depends upon
the format being used.
- fixed precision sets the number of digits after the
decimal to display.
- scientific precision sets the number of significant
digits to use.
In either case the number is always rounded when printed not
truncated.
- void fill(char c) changes the padding character to
c. Note that the default padding character is a space.
The fill character remains in effect until changed.
- C++ provides some manipulators that do the same thing as the format
methods listed in the previous section. Manipulators may be inserted
using the insertion (<<) operator rather than calling the method
using an ostream object, and so are more convienient to use.
You must use #include <iomanip> to use these.
- setw(int) does the same thing as the width method.
- setprecision(int) does the same thing as the
precision method.
- setfill(char c) does the same thing as the fill
method.
- setiosflags(long) does the same thing as the setf
method.
- unsetiosflags(long) does the same thing as the
unsetf method.
The ISO standard also defines manipulators, fixed, scientific,
left and right among others which can be used to set
formats without calling setiosflags BUT our g++ compiler
does not implement them yet. The Sun C++ compiler does. But be
warned that not all compilers implement these yet.
- The ifstream class is used to provide input from a file
other than the standard input file. To use the ifstream
class, you must use #include <fstream>. To use a file
for input, you must declare an ifstream object and then
attach it to a disk file. Once this has been done, the object can be
used in the same way that the cin object is used. The
>> operator and all the input stream methods may be used
with the ifstream object. In addition, two more methods are
provided :
- open(char[] filename) attaches the file named
filename to the ifstream object. If the file
can not be attached, the method returns false. If the file is
successfully attached, the marker is set at the first
character in the file. Note that the parameter must be an
array of characters. If the file name is stored in a
string, then you must convert it to an array using the
string method c_str().
- close() detaches the file from the ifstream object.
You should always close a file as soon as you have
finished extracting from it.
If the filename is known, then the attachment can be done on
declaration by including the name as a parameter.
eg ifstream iStr("myfile");
- The ofstream class is used to provide output to a file
other than the standard output file. To use the ofstream
class, you must use #include <fstream>. To use a file
for output, you must declare an ofstream object and then
attach it to a disk file. Once this has been done, the object can be
used in the same way that the cout object is used. The
<< operator and all the output stream methods may be used
with the ofstream object. In addition, two more methods are
provided :
- open(char[] filename) attaches the file named
filename to the ofstream object. If the file
does not exist, it is created. If the file does exist, the
marker is set at the front of the file and the file is
emptied. Note that the parameter must be an
array of characters. If the file name is stored in a
string, then you must convert it to an array using the
string method c_str().
- close() detaches the file from the ofstream object.
You should always close a file as soon as you have
finished inserting to it.
If the filename is known, then the attachment can be done on
declaration by including the name as a parameter.
eg ofstream oStr("myfile");