Code
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
// This is the main function
int main()
{
ifstream fin("temperature.txt");
ofstream fout("average.txt");
while ((!fin.eof()))
{
string date;
// This variable stores the temperature read from the file
double temperature=0;
// This variable stores the average temperature for a day
double average_temperature=0;
// Reading the date from the file
fin >> date;
// Reading 24 temperatures from the file
for(int i=0;i<24;i++)
{
// Reading a temperature
fin >> temperature;
// Adding the read temperature to average_temperature
average_temperature += temperature;
}
// Calculating the average temperature
average_temperature /= 24;
// Writing the date followed by a space and precision is set to 1, then writing average temperature with a end line to the output file
fout << date << " "<< fixed << setprecision(1) << average_temperature << endl;
}
}
Actual Output
Testing result with "cat average.txt":
2019/02/28 20.7
2019/03/01 20.1
2019/03/02 21.4
2019/03/03 21.6
2019/03/04 20.8
2019/03/05 22.7
2019/03/06 21.4
2019/03/07 18.0
2019/03/08 17.6
2019/03/09 20.7
2019/03/10 16.7
2019/03/11 18.4
2019/03/12 19.8
2019/03/13 21.1
0.0
Expected Output
Testing result with "cat average.txt":
2019/02/28 20.7
2019/03/01 20.1
2019/03/02 21.4
2019/03/03 21.6
2019/03/04 20.8
2019/03/05 22.7
2019/03/06 21.4
2019/03/07 18.0
2019/03/08 17.6
2019/03/09 20.7
2019/03/10 16.7
2019/03/11 18.4
2019/03/12 19.8
2019/03/13 21.1
Hi. I was trying to work on a question but somehow the program printed an additional 0.0 at the very last line which I do not want. I just started to learn file inputs and outputs for C++ so I'm not sure how a 0.0 appeared in the program.
You can observe that in the actual output, there is a 0.0 at the last line but I want to remove this which I do not know how.