8.10. LAB 2 (Part 1): File I/O - Sum of integers Implement the function fileSum.
ID: 3815136 • Letter: 8
Question
8.10. LAB 2 (Part 1): File I/O - Sum of integers
Implement the function fileSum. fileSum is passed in a name of a file. This function should open the file, sum all of the integers within this file, close the file, and then return the sum. If the file does not exist, this function should output an error message: "Error opening ..." and then call the exit function to exit the program with an error value of 1.
code template//
#include <fstream>
#include <iostream>
#include <cstdlib> //needed for exit function
using namespace std;
// Place fileSum prototype (declaration) here
int main() {
string filename;
cout << "Enter the name of the input file: ";
cin >> filename;
cout << endl;
cout << "Sum: " << fileSum(filename) << endl;
return 0;
}
// Place fileSum implementation here
Explanation / Answer
#include <fstream>
#include <iostream>
#include <cstdlib> //needed for exit function
using namespace std;
// Place fileSum prototype (declaration) here
int fileSum(string filename) ;
int main() {
string filename;
cout << "Enter the name of the input file: ";
cin >> filename;
cout << endl;
cout << "Sum: " << fileSum(filename) << endl;
return 0;
}
// Place fileSum implementation here
int fileSum(string filename) {
ifstream inputFile;
inputFile.open(filename.c_str());
int n;
int sum = 0;
if (inputFile.is_open()) {
while (!inputFile.eof()) {
inputFile >> n;
sum = sum + n;
}
}
else{
cout<<"Error opening ..."<<endl;
}
inputFile.close();
return sum;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter the name of the input file: text.txt
Sum: 55
text.txt
1
2
3
4
5
6
7
8
9
10
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.