EOF Loops
Video Summary: https://youtu.be/6YdGL4Vu0ZE
While loops can help you process all the data in a file without knowing how long the file is in advance.
We know any of the following can cause an input stream to enter the fail state:
- Invalid input data
- An attempt to read beyond the end of a file
- An attempt to open a nonexistent file to input
C++ provides a way to test the state of a stream: The stream name used in
the expression returns true
value if the state is ok and
false
value if the state is in the fail state.
When the test expression returns a false
value, the program
terminates. When it returns a true
value, the program continues
reading the data item from the file. Here is a sample program that reads
floating point data values from a file and outputs the sum and average of
the numbers.
Notice that inData
and outData
are identifiers in
the program;
"Input.txt"
and "Output.txt"
are character
strings.
Input.txt
is the name that was used when the input data file was
created; Output.txt
is the name of the file where the answers are
stored.
If the input file Input.txt
cannot be found, 1 is returned to the
operating system. If the output file Output.txt
cannot be opened or
created, 2 is returned to the operating system. If there is no input and
output error, 0 is returned to the operating system. Notice that the
main()
program is exited as soon as a value is returned. Therefore,
returning 0 value means normal completion of a program; and returning any
other value signals an error. When you write your own program, you may
choose the value to return to indicate different error conditions.
While input data file has correct data items, the program will read the data, and sum up the values, and record the number of items read until the EOF is encountered.
You can use your favorite text editor to create the input data file according to the requirements of the data type and the format specified in your program. The input data file must exist and contain correct data. Otherwise, the input stream will fail.
For example, in the preceding IODemo program, the input file look like this:
3.2 4.6 5.5 6.6 7.7 8.8 9.8
Run the program and find the sum and average of your input data.