Working on an exercise that asks to find sum of numbers in file while ignoring invalid input, i.e. "bears: 17 elephants 9 end" would output 26. Right now when reading the file the input terminates as soon as it encounters an error, and I've been trying to find how to get around that. I'm sure the problem is at the ist.fail() part at read_file.
void read_file(string iname, vector<int>& result) {
ifstream ist {iname}; // ist reads from the file named iname
if (!ist) error("can't open input file ",iname);
for (int temp; ist >> temp; )
result.push_back(temp);
if (ist.fail()) {
ist.clear(ios_base::failbit);
}
}
void write_file(string& oname, string& input1, const vector<int>& result) {
ofstream ost {oname}; // ost writes to a file named oname
if (!ost) error("can't open output file ",oname);
double sum = 0;
for (int i=0; i<result.size(); ++i)
sum += result[i];
ost << sum;
}
int main()
{
string input = "a.txt";
string output = "b.txt";
vector<int> result;
read_file(input, result);
write_file(output, input, result);
}
Aucun commentaire:
Enregistrer un commentaire