IO class methods and operators


Here is the simplified class hierarchy for Input/Output in C++.
                        ios
                       /   \
                      /     \
                     /       \
                    /         \
                istream    ostream
		   / \       / \
                  /   \     /   \
                 /     \   /     \
                /       \ /       \
           ifstream  iostream  ofstream
  1. To use the iostream class, you must use #include <iostream>

  2. The iostream class has three objects that you can use:
    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 a set of flags which can be used to determine whether the extraction was successful.
    1. We use the extraction operator(>>) to read data from an input stream. This operator has the following behaviours:
      1. It skips over all leading whitespace (spaces, tabs and new lines).
      2. It can be cascaded. eg
                  cin >> a  >> b  >> c;
        is the same as
                  cin >> a;
                  cin >> b;
                  cin >> c;
              
      3. It extracts characters one at a time and advances the reading marker.
      4. 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 at end of file.
        2. 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.
        3. 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.
        4. 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.
      5. 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 reading marker is not advanced.
    2. An input stream object has the following methods:
      1. void get(char& c) — extracts the next character from the input stream and stores it in c.
      2. char get() — extracts the next character from the input stream and returns it.
      3. 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.
      4. void ignore(int n) — extracts the next n characters or until the marker finds an end of file whichever comes first.
      5. void ignore(int n, char c) — extracts the next n characters or until the marker finds the character c whichever comes first.
      6. char peek() — returns the character that the marker is pointing at but does not advance the marker.
      7. 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.
      8. bool good() — returns true if the last extraction was successful, false otherwise.
      9. bool fail() — returns true if the last extraction was not successful and no data was lost; false otherwise.
      10. bool bad() — returns true if the last extraction was not successful, but data was lost; false otherwise.
      11. bool eof() — returns true if the last extraction found the end of file, false otherwise.
      12. 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.
      13. 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
      14. 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.
      15. 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.
      16. 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.

  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 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 or string values.
      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. 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.

  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 BUT some compilers have not implemented them yet. The version of the g++ compiler that we use implements them. 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 ifstream and ofstream classes provide methods to find where the file marker is (tell) and to reposition it (seek).
    1. tellg() - returns the position of the file marker in an ifstream
    2. tellp() - returns the position of the file marker in an ofstream
    3. seekg(pos) - sets the position to pos in an ifstream
    4. seekp(pos) - sets the position to pos in an ofstream
    5. seekg(offset, where) - sets the position to where+offset in an ifstream. offset can be negative.
    6. seekp(offset, where) - sets the position to where+offset in an ofstream. 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 file marker.