Average Rainfall
Write a program that calculates the average rainfall for three months. The program should ask the user to enter the name of a data file that that contains rainfall data for three months. The file consists of three lines, each with the name of a month, followed by one or more spaces, followed by the rainfall for that month. The program opens the file, reads its contents and then displays a message like:
The average rainfall for June, July, and August is 6.72 inches.
Prompts And Output: The program prompts the user with the string "Enter filename with monthly data: ". The output should be of the form: "The average rainfall for MONTH1, MONTH2, and MONTH3 is: AVERAGE" where MONTH1, MONTH2, and MONTH3 are the month names that were read from the datafile user and where AVERAGE is the average rainfall calculated from the file's rainfall data and shown with exactly two digits past the decimal point.
I did;
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char month1[8], month2[8], month3[8];
double rainfall, avg_Rainfall;
double totalRainfall = 0; //create a variable to hold the total rainfall
cout << "How much inches of rain fell in " << month1 << "?" << endl;
cin >> rainfall;
totalRainfall += rainfall; //add this month's rainfall to the total rainfall, then store the result back into totalRainfall, ie:
// totalRainfall = totalRainfall + rainfall;
cout << "How much inches of rain fell in " << month2 << "?" << endl;
cin >> rainfall;
totalRainfall += rainfall; //same thing here
cout << "How much inches of rain fell in " << month3 << "?" << endl;
cin >> rainfall;
totalRainfall += rainfall; //and here
avg_Rainfall = totalRainfall / 3; //now calculate the average
//...
system("pause");
return 0;
}
But the expected output should be
Enter·filename·with·monthly·data:↵
The·average·rainfall·for·January,·February,·and·March·is·20.33·inches.↵
You are supposed to read the filename not the name of the months.
Then you should read the month names and numbers from the file, not from the keyboard.
Here's a skeleton to get you started.
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
string filename, month1, month2, month3;
double total = 0, avg = 0, temp1 = 0, temp2 = 0, temp3 = 0;
cout << "Enter filename with monthly data: ";
getline(cin, filename);
ifstream src(filename);
//ifstream src(filename.c_str()); for older compiler
if (!src)
{
cout << "\n*** Error opening file. ***\n";
return 1;
}
// TO DO
// read the name of month and temperature - maybe in a for loop,
// and add temperature to total
// calculate avg and display results
}