//-------------------------------------------------------------------- // // Example showing the use of the eof() function eof.cpp // //-------------------------------------------------------------------- // Reads ALL the integer values from a user-specified input file and // displays their sum. #include // For cin and cout #include // For file input/output void main() { ifstream inFile; // Input file stream char filename[21]; // Input file name int num, // Number read from file sum = 0; // Sum of numbers read in // Get the file name. cout << "Enter file name (try values.dat): "; cin >> filename; // Open the input file. inFile.open( filename,ios::nocreate ); // Check that input file opened correctly. if ( !inFile ) cout << "File " << filename << " could not be opened for input" << endl; else { cout << endl; // Read in numbers, compute their sum, and output the result. while ( !inFile.eof() ) // <<<<<<< INCORRECT approach !!!!!!! { inFile >> num; cout << num << ' '; sum += num; } cout << endl << "Sum = " << sum << endl << endl; // Reset the file pointer to the start of the file. inFile.seekg(0); // Reset pointer inFile.clear(); // Clear file flags (including eof) // Read in numbers, compute their sum, and output the result. sum = 0; while ( !inFile.eof() ) // <<<<<<< Awkward (correct) approach { inFile >> num; if ( !inFile.eof() ) { cout << num << ' '; sum += num; } } cout << endl << "Sum = " << sum << endl << endl; // Reset the file pointer to the start of the file. inFile.seekg(0); // Reset pointer inFile.clear(); // Clear file flags (including eof) // Read in numbers, compute their sum, and output the result. sum = 0; inFile >> num; while ( !inFile.eof() ) // <<<<<<< Better correct approach { cout << num << ' '; sum += num; inFile >> num; } cout << endl << "Sum = " << sum << endl << endl; // Reset the file pointer to the start of the file. inFile.seekg(0); // Reset pointer inFile.clear(); // Clear file flags (including eof) // Read in numbers, compute their sum, and output the result. sum = 0; while ( inFile >> num ) // <<<<<<< Another correct approach { cout << num << ' '; sum += num; } cout << endl << "Sum = " << sum << endl << endl; // Close the input file stream. inFile.close(); } }