File streams
Exercise 10.1
Write a program that reads from a file named
input.txtcontaining numbers separated by newlines and writes the sum of the numbers at the end of the file. You may assume that each line of the file consists of exactly one number.For example, if
input.txtcontains1.1 2.3 3.1 0.2then after running the program,
input.txtshould contain1.1 2.3 3.1 0.2 6.7Solution
Here is one possible solution.
#include <fstream> using namespace std; int main() { ifstream input("input.txt"); double sum = 0; double number; while (input >> number) { sum += number; } ofstream output("input.txt", ofstream::app); output << sum << endl; return 0; }Remark: The opening mode flag
ofstream::appcould be written equivalently asios_base::app,ios::app, orostream::app.Alternative solution
Here is another possible solution, using a single
fstreaminstead of anifstreamand anofstream.#include <fstream> using namespace std; int main() { fstream file("input.txt"); double sum = 0; double number; while (file >> number) { sum += number; } file.clear(); file << sum << endl; return 0; }Note that
clearis used to reset the stream’s error state flags so that the file can be written to after its end has been encountered.