- Specified Number of Records
- One of the easiest ways is to first read in a number indicating how many data items to read in, and then read in that many data items:
int nData;
double x, y, z;
fin >> nData;
for( int i = 0; i < nData; i++ ) {
fin >> x >> y >> z;
// Do something with x, y, z
} for loop reading input data
- The difficulty with this method is that the number of data items present must be know when the file is created.
- Sentinel Value
- Another commonly used method is to look for a special value ( combination ) as a trigger to stop reading data:
double x, y;
while( true ) {
fin >> x >> y;
if( x = = 0.0 && y = = 0.0 )
break;
// Do something with x and y
} // while loop reading input data
- The difficulty with this method is that the sentinel value must be carefully chosen so as not to be possible as valid data.
- Detect End of File
- If you know that the data you are reading goes all the way to the end of the file ( i.e. there is no other data in the file after the data you are reading ), then you can just keep on reading data until you detect that the end of the file has been reached.
- All istreams ( and ifstreams ) have a method, eof( ), that returns a boolean value of true AFTER an attempt has been made to read past the end of the file, and false otherwise.
- Because the true value isn't set until AFTER you have gone too far, it is important to: (1) read some data first, then (2) check to see if you've gone past the end of the file, and finally (3) use the data only after you have verified that the reading succeeded. Note carefully in the following code that the check for the end of file always occurs AFTER reading the data and BEFORE using the data that was read:
double x, y, z;
fin >> x >> y >> z;
while ( !fin.eof( ) ) {
// Do something with x, y, z
// Read in the new data for the next loop iteration.
fin >> x >> y >> z;
} // while loop reading until the end of file