A very common usage of loops is the repetitive reading of data . This reading may be from the keyboard or from an existing data file which contains a long list of numbers. In the case of reading from a data file, an approach is to let the program read to the end of the file or until an improper data field is encountered.
|
|
mydata.eof( ) | will evaluate to TRUE when we reach the end of file ( immediately after mydata >> ..) |
mydata.fail( ) |
will evaluate to TRUE when improper data is encountered ( immediately after mydata >> ..) |
The following is an annotated example for several numbers, which are read from a file and outputted to the screen, while their sum is calculated. |
Initial comments |
/* input file failure example file: 3ex3.cpp FALL 2001 ___________________________________ Jacob Y. Kazakia jyk0 May 2, 2001 Programming example 3 of unit #3 Recitation Instructor: J.Y.Kazakia Recitation Section 01 ___________________________________ Purpose: This program reads a sequence of numbers, which are written in a file called 3ex3data.txt The file looks like this: 1.00345 4.567 1.89e-03 2.345 1.78 2.897e-6 123.678 34 We assume that the user does NOT know, ahead of time, how many numbers are listed. The task of the program is to output the numbers to the screen and calculate the sum. Algorithm: A stream named ex3input is established. A while loop provides repeated reading of numbers. The condition of the loop is set to: while ( ! ex3input.eof( ) ) When the stream 3ex3input reaches the END OF FILE the ex3input.eof( ) evaluates to TRUE. As long as we are not at the end it evaluates to FALSE and consequently the prefixed ! is needed. */ |
The fstream.h header can support both file and default I/O The stream report is created |
#include |
Variables are declared and initialized The first number is read The heading of the list is created |
float number ; float sum = 0; ex3input >> number; cout << "\n\n This is the list of numbers read \n\n"; |
The while loop. It will run as long as there are numbers to
be read Note that the reading of the next number is done as the last statement |
while ( ! ex3input.eof( ) ) // read the numbers and add them up { cout << number << endl; sum = sum + number; ex3input >> number; } |
When the end of file is reached, the while loop terminates and the statements beyond the bracket are executed |
cout << "\n\n End of file reached. The sum is : " ; cout << sum; cout << " \n\n Enter e(exit) to exit ..."; char hold; cin >> hold; } |
Note that the numbers are read as the file is scanned from
left to right in the first line and then the second line and the third and
so on until the end of file is reached. We will discuss selective reading later in the course. |
/* THE OUTPUT : This is the list of numbers read 1.00345 4.567 0.00189 2.345 1.78 2.897e-006 123.678 34 End of file reached. The sum is : 167.375 Enter e(exit) to exit ... */ |