//-------------------------------------------------------------------- // // Example showing the use of the open() function infile2.cpp // //-------------------------------------------------------------------- // Reads the first five 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; // Alternate method of opening an input file. // flag ios::nocreate indicates that the file open // operation should fail if there is no such 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 { // Read in numbers and compute their sum. for ( int j = 0 ; j < 5 ; j++ ) { inFile >> num; cout << num << endl; sum += num; } // Output the sum. cout << "Sum = " << sum << endl << endl; // Close the input file stream. inFile.close(); } }