Save numbers to a file, then read them back.
What to build
A program that writes a file and reads it.
Requirements
- Write each input number to
data.txt, on its own line. - Close the file, open it again for reading, and read all the numbers from it.
- Print
count Candsum S.
Input
The first line has n. The second line has n whole numbers.
Output
Two lines.
Constraints
n is from 0 to 100. When n is 0, the second line is empty.
Example
Input:
3
1 2 3
Output:
count 3
sum 6
Why it works
The read loop stops when the file runs out, so it never needs to be told how many numbers there are.
Examples
Example 1 · Input
3 1 2 3
Expected output
count 3 sum 6
Example 2 · Input
0
Expected output
count 0 sum 0
Hints
Hint 1
Use an ofstream to write, and close it.
Hint 2
Use an ifstream to read, with while (in >> x).
Solution
Show one correct solution (try it yourself first)
#include <fstream>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
ofstream out("data.txt");
for (int i = 0; i < n; i++) {
int x;
cin >> x;
out << x << endl;
}
out.close();
ifstream in("data.txt");
int x, count = 0, sum = 0;
while (in >> x) {
count++;
sum += x;
}
cout << "count " << count << endl;
cout << "sum " << sum << endl;
return 0;
}