next up previous
Next: ostream methods Up: The ostream, istream, ofstream Previous: C++ and Unix I/O

istream methods

For the first example, we show how to use istream methods to read a list of numbers up to an end-of-file, checking for errors, without knowing in advance exactly how many there are:

#define MAX 100
int main(){
  double a[MAX];
  int n;

  n = 0;
  while(n < MAX){
     cin >> a[n];
       cerr << "Data item number " << n+1 << " has bad numeric format\n";
       return 1;

The identifier cin is an instance of the istream class. Its eof() method returns true if the input stream has run out of data. (If the input came from the keyboard, a Unix user signaled an end of data with Ctrl-d. If it was redirected from a file, the end of file was reached.)

Similarly the fail() method returns true if the input operation failed for any reason. This includes an end-of-file condition and a formatting error: e.g., attempting to read nondecimal characters. In the logic above, we break from the loop if the read failed because of an end of file condition and complain otherwise.

Carleton DeTar 2008-11-10