COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
report_temperature.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <fstream>
3#include <sstream>
4#include <string>
5#include <iomanip>
6using namespace std;
7
8
9int main() {
10 // ifstream is input file stream, ofstream is output file stream
11 ifstream file; // or ifstream file ("temperature.txt"); syntax also works
12 file.open("temperature.txt");
13 if (file.fail()) {
14 cout << "Error in file opening!" << endl;
15 exit(1);
16 }
17 ofstream average_file;
18 average_file.open("average.txt");
19 if ( average_file.fail() ) {
20 cout << "Error in file opening!" << endl;
21 exit(1);
22 }
23 string one_line;
24 average_file << fixed << setprecision(1);
25 // for each line
26 while(getline(file, one_line)){
27 string date;
28 int count = 0;
29 double sum = 0;
30 istringstream line_stream(one_line);
31 line_stream >> date;
32 double temperature;
33 // for each temperature in the line (total 24 temps)
34 while(line_stream >> temperature){
35 sum += temperature;
36 count++;
37 }
38 double average = sum / count;
39 average_file << date << " " << average << endl;
40 }
41 file.close();
42 average_file.close();
43 return 0;
44}
int main()