我有一个读取文件并返回文件中数字总和的函数。我正在检查文件是否存在。如果它不存在,我将返回1。但是我的问题是计算和的函数的返回值是int。因此,如果无法打开文件,它将返回1作为总和,而我希望它返回1作为错误指示符而不是总和。
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int sum (string filename);
int main() {
string filename;
cout << "Enter the name of the input file: ";
cin >> filename;
cout << "Sum: " << fileSum(filename) << endl;
return 0;
}
int sum(string filename) {
int num = 0;
int sum = 0;
ifstream in;
in.open(filename.c_str());
if(!in.is_open()) {
cout << "Error opening " << filename << endl;
return 1;
}
in >> num;
cout << "File contains the …Run Code Online (Sandbox Code Playgroud)