- 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 true if the extraction was successful; false
otherwise. We can use the stream as a boolean. eg
cin >> x;
if (cin) ...
- 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 if there is no data to be read (ie 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 or it runs out of data.
If whitespace is found, then the marker is left pointing
at the whitespace. If it runs out of data, then the eof flag is
set but the stream still returns true.
It only fails if there is no data to be read (ie 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 or it runs out of data.
If whitespace is found, then the marker is left pointing
at the whitespace. If it runs out of data, then the eof flag is
set but the stream still returns true.
It only fails if there is no data to be read (ie 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 or it runs
out of data. The string is then converted to the appropriate
type. If it runs out of data, the eof flag is set but the stream
still returns true. If it did not run out of data, then the
marker is left pointing at the invalid character. It
fails if no characters were extracted or the extracted characters
could not be converted to the appropriate type.
- 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 width(int n) restricts the next extraction to at most
n-1 characters (must have room for '\0'). After each
extraction, the width is reset to the default value. This is
commonly used with the extraction operator(>>) to prevent
overflow of a character array.
- void get(char& c) extracts the next character from the input
stream and stores it in c. It fails if there is no data.
If it fails, the eof flag is set and the stream returns false.
- char get() extracts the next character from the input stream
and returns it. It fails if there is no data. If it fails, the eof
flag is set and the stream returns false.
- 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. It fails if there
is no data to be ignored. If it fails, the eof flag is set and the
stream returns false.
- void ignore(int n) extracts the next n characters or
until there is no more data whichever comes first. If there is no
more data, the eof flag is set and the stream returns false.
- void ignore(int n, char c) extracts the next n
characters or until the marker finds the character
c, or it runs out of data whichever comes first.If it runs
out of data, the eof flag is set and the stream returns false.
- char peek() returns the character that the marker is
pointing at but does not advance the marker. If there is
no data, the eof flag is set and the stream returns false.
- 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. This function will
do nothing if the stream has an error flag set.
- bool good() returns true if the last extraction was
successful and it did not run out of data; 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 even if the extraction was successful; 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-1 characters have been extracted, whichever
occurs first. Note that a '\0' character is inserted as the last
in the array.
- void getline(char[] carray, int n) same as the
previous get except that the marker is moved
past the new line character. The new line character is not
stored.
- 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-1 characters have
been extracted, whichever occurs first. Note that a '\0' character
is inserted as the last in the array.
- 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.
- void read(char[] carray, int n) extracts characters and
stores them in carray until n characters have
been extracted. It does not insert a '\0' character into
the array.
- 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, but not including, 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 variables.
- 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.
- char 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. It returns
the fill character that was in effect prior to the change. You
may store the return value to
be used to reset the fill character to its original value.
- 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 in iostream, fixed,
scientific, left and right among others, which can be
used to set formats without calling setiosflags. eg.
- cout << fixed; is the same as
cout << setiosflags(ios::fixed);
- 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 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");
If the stream was not successfully attached, either by the open
method or in a declaration, the stream can be tested and
will be false. eg
if (iStr)
// file was successfully attached;
else
// file was not successfully attached;
- 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");
If the stream was not successfully attached, either by the open
method or in a declaration, the stream can be tested and
will be false. eg
if (oStr)
// file was successfully attached;
else
// file was not successfully attached;
- The istringstream class is used to provide input from a string.
To use the istringstream
class, you must use #include <sstream>. To use a string
for input, you must declare an istringstream object and insert
a string into the stream. 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 istringstream object. In addition, two more methods
are provided :
- void str(const string& s) inserts s into the stream.
- string str() returns the string that is in the stream
You may insert a string into a stream on declaration by including the
string as a parameter. eg istringstream in("Hello"); declares
in as a stringstream and inserts the word Hello into
it.
- The ostringstream class is used to provide input from a string.
To use the istringstream
class, you must use #include <sstream>. To use a string
for output, you must declare an ostringstream object. 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 ostringstream object. In addition, two more methods
are provided :
- void str(const string& s) inserts s into the stream.
- string str() returns the string that is in the stream
Using the << operator just appends items to the stream. You may
use the str(s) method to clear an ostringstream. eg
out.str(""); will clear the out object.
- The fstream and stringstream classes allow you
to read and write from the same file or string.
- the istream and ostream classes provide methods to
find where the file marker is (tell) and to reposition it
(seek). These only make sense if the stream is attached to
something for which positioning is meaningful, such as a file.
- tellg() - returns the position of the input marker
- tellp() - returns the position of the output marker
- seekg(pos) - sets the position to pos for input
- seekp(pos) - sets the position to pos for output
- seekg(offset, where) - sets the position to where+offset
for input. offset can be negative.
- seekp(offset, where) - sets the position to where+offset
for output. offset can be negative.
- where must be one of:
- ios::beg - the beginning of the file
- ios::end - the end of the file
- ios::cur - the actual position of the marker.