// // sumfile3.cpp // CSC 215 // John Rogers // // This program reads a list of integers from a // file and outputs their sum. Unlike sumfile2.cpp, // it asks the user for the name of the file containing // the numbers. // // // 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; char inputfileName[51]; // Assume that the name is 50 chars or less. ifstream inputfile; // // Connect the input file stream object inputfile // to the file whose name is given by the user. // Exit the program if the open failed. // cout << "Enter the pathname of the file containing the numbers: "; cin >> inputfileName; inputfile.open(inputfileName); if (inputfile.fail()) { cout << "Unable to open the file " << inputfileName << 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; }