File streams
Exercise 10.1
Write a program that reads from a file named
input.txt
containing 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.txt
contains1.1 2.3 3.1 0.2
then after running the program,
input.txt
should contain1.1 2.3 3.1 0.2 6.7
Solution
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::app
could be written equivalently asios_base::app
,ios::app
, orostream::app
.Alternative solution
Here is another possible solution, using a single
fstream
instead of anifstream
and 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
clear
is used to reset the stream’s error state flags so that the file can be written to after its end has been encountered.