IO class methods and operators


Here is the simplified class hierarchy for Input/Output in C++.
                              ios
                             /  \
                            /    \
                           /      \
                          /        \
                       istream    ostream
           __________/   / \       / \   \__________
          /             /   \     /   \             \
         /             /     \   /     \             \
        /             /       \ /       \             \
  istringstream  ifstream  iostream  ofstream  ostringstream
                            /   \
                           /     \
                          /       \
                         /         \
                     fstream   stringstream 

  1. To use the iostream class, you must use #include <iostream>

  2. The iostream class has three public objects:
    1. cin — which is attached to the standard input stream (an istream)
    2. cout — which is attached to the standard output stream (an ostream)
    3. cerr — which is attached to the display stream (an ostream)

  3. 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.
    1. We use the extraction operator(>>) to read data from an input stream. This operator has the following behaviours:
      1. It returns true if the extraction was successful; false otherwise. We can use the stream as a boolean. eg
                       cin >> x;
        	       if (cin) ...
                 
      2. 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:
        1. 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).
        2. 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.
        3. 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).
        4. 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.
        5. 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.
      3. 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.
    2. An input stream object has the following methods:
      1. 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.
      2. 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.
      3. 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.
      4. 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.
      5. 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.
      6. 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.
      7. 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.
      8. 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.
      9. bool good() — returns true if the last extraction was successful and it did not run out of data; false otherwise.
      10. bool fail() — returns true if the last extraction was not successful and no data was lost; false otherwise.
      11. bool bad() — returns true if the last extraction was not successful, but data was lost; false otherwise.
      12. bool eof() — returns true if the last extraction found the end of file even if the extraction was successful; false otherwise.
      13. 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.
      14. 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
      15. 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.
      16. 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.
      17. 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.
      18. 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.
      19. 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.

  4. 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.
    1. We use the insertion operator(<<) to write data to an output stream. This operator has the following behaviours:
      1. Only characters are inserted into the stream.
      2. It can be cascaded eg cout << a << b << c;
      3. 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:
        1. char — the character is inserted into the stream.
        2. char[] — each character in the array is inserted up to, but not including, the '\0' character.
        3. string — each character in the string is inserted.
        4. numeric — the number is converted to a temporary string and then each character is inserted.
        5. bool — if the value is true the character '1' is inserted; if the value is false the character '0' is inserted.
    2. The stream is not flushed, that is written, until one of the following conditions is met:
      1. An istream object is used. This is useful for prompts.
      2. An endl is inserted. endl comes from the iostream class and when inserted, inserts a new line character and flushes the stream.
      3. A newline('\n') is inserted.
      4. A flush is inserted. flush comes from the iostream class and when inserted it flushes the stream but does not insert a newline.
    3. An output stream has the following methods.
      1. void put(char c) — inserts the character c into the output stream.
      2. 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.
      3. 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:
        1. ios::fixed — floating point values will be written in fixed decimal format
        2. ios::scientific — floating point values will be written in scientific notation i.e. using e notation.
        3. ios::left — values will be left justified in the field.
        4. ios::right — values will be right justified in the field.
      4. long unsetf(long n) — resets the specified flag and returns the value the flag had prior to being reset.
      5. 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.
        1. fixed — precision sets the number of digits after the decimal to display.
        2. scientific — precision sets the number of significant digits to use.
        In either case the number is always rounded when printed not truncated.
      6. 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.

  5. 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.
    1. setw(int) — does the same thing as the width method.
    2. setprecision(int) — does the same thing as the precision method.
    3. setfill(char c) — does the same thing as the fill method.
    4. setiosflags(long) — does the same thing as the setf method.
    5. 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.

  6. 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 :
    1. 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().
    2. 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;
           

  7. 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 :
    1. 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().
    2. 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;
           

  8. 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 :
    1. void str(const string& s) — inserts s into the stream.
    2. 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.

  9. 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 :
    1. void str(const string& s) — inserts s into the stream.
    2. 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.

  10. The fstream and stringstream classes allow you to read and write from the same file or string.

  11. 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.
    1. tellg() - returns the position of the input marker
    2. tellp() - returns the position of the output marker
    3. seekg(pos) - sets the position to pos for input
    4. seekp(pos) - sets the position to pos for output
    5. seekg(offset, where) - sets the position to where+offset for input. offset can be negative.
    6. seekp(offset, where) - sets the position to where+offset for output. offset can be negative.
    7. 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.