// // sumfile2.cpp // CSC 215 // John Rogers // // This program reads a list of integers from a // file and outputs their sum. Unlike sumfile.cpp, // this program verifies that it has actually opened // the file. // // // iostream.h is needed to allow input from cin and output to cout. // #include // // fstream.h is needed to allow the use of file stream objects, ie, // objects from the classes ifstream and ofstream. // #include // // stdlib.h is needed to allow the use of the exit() function. // #include int main() { int sum = 0, number; ifstream inputfile; // // Connect the input file stream object inputfile // to the file numbers.dat. Exit the program if // the open failed. // inputfile.open("numbers.dat"); if (inputfile.fail()) { cout << "Unable to open the input file." << endl; exit(1); } // // Read the integers in inputfile, adding each // to sum. // while (inputfile >> number) { sum += number; } cout << "The sum is " << sum << endl; inputfile.close(); return 0; }