next up previous
Next: Formatting output Up: iomethods Previous: C++ and Unix I/O

Some istream methods: eof and fail

Here we discuss two useful istream methods - one for checking for an end of file and another for checking for data format errors.

A keyboard end of file is signaled by typing Ctrl-d. For a regular file it occurs when attempting to read past the last byte. Here is an example of its use:

  float a[MAX];
  while(n < MAX){
    cin >> a[n];
    if(cin.eof())break;
    n++;
  }
Notice that we use the dot . operator to access the class member. Be sure to include the () because eof is a member function or method. It returns true if the last cin operation hit an end of file before finding any data. In this example the value of n after the end of file is the number of data items read into the array a.

A formatting error occurs when attempting to read a number containing improper characters, e.g. attempting to create an integer from the string 3.14. With cin formatting errors are silent and potentially deadly. That is, there is no error message and the no input value is stored. So it is a good idea to check for them.

For this purpose the class method fail() returns true when the last read operation encountered an error. For example, we could improve the above code by replacing the line cin >> a[n] with

    cin >> a[n];
    if(cin.fail()){
      cerr << "Error reading a[" << n << "]\n";
    }


next up previous
Next: Formatting output Up: iomethods Previous: C++ and Unix I/O
Carleton DeTar 2007-10-31