In: Computer Science
using C++
24. Using Files—Total and Average
Rainfall
Write a program that reads in from a file a starting month name, an
ending month name,
and then the monthly rainfall for each month during that period. As
it does this, it should
sum the rainfall amounts and then report the total rainfall and
average rainfall for the
period. For example, the output might look like this:
During the months of March–June the total rainfall was 7.32 inches
and the average
monthly rainfall was 1.83 inches.
Data for the program can be found in the Rainfall.txt file.
Hint: After reading in the month names, you will need to read in
rain amounts until
the EOF is reached, and count how many pieces of rain data you read
in.
You can use note pad to create a Rainfall.txt with the following data:
January
May
1.35 2.15 3.03 4.41 5.41
Please note that you must read the first line of the file as starting month and second line as ending month. Please do not hard code the starting and ending month into your program.
test case
During the months of January-May the total
rainfall was 16.35 inches and the average monthly
rainfall was 3.27 inches.
Thanks for the question, here is the simple C++ program to read from the file and displays the total and average rainfalls
When you run the program, please update the below line for the file name path in your system
char * filename ="Rainfall.txt";
else it wont be able to read the file and display the output.
=====================================================================
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
#include<cstdlib>
using namespace std;
int main(){
char * filename ="F:\\Rainfall.txt";
ifstream infile(filename);
double total_rainfall=0;
int months=0;
string startMonth;
string endMonth;
if(infile.is_open()){
double rainfall;
infile>>startMonth>>endMonth;
while(infile>>rainfall){
total_rainfall+=rainfall;
months+=1;
}
infile.close();
}else{
cout<<"Unable to read data
from file: "<<filename<<endl;
exit(EXIT_FAILURE);
}
cout<<"During the months if
"<<startMonth<<"-"
<<endMonth<<" the total \nrainfall was
"
<<fixed<<showpoint<<setprecision(2)
<<total_rainfall<<" inches and the average
monthly \nrainfall was "
<<total_rainfall/months<<"
inches."<<endl;
}