Write your question here.
Hello folks, I am not able to find the average arrays from my .txt file. Is there any solution to this?
Thank you for your time!
/*In the student sample programs for this book, you will find a text file named 1994_Weekly_Gas_Averages.txtPreview the document.
The file contains the average gas price for each week in the year 1994 (There are 52 lines in the file.
Line 1 contains the average price for week 1, line 2 contains the average price for week 2, and so forth.)
Write a program that reads the gas prices from the file into an array or a vector. The program should do the following:
Display the lowest average price of the year, along with the week number for that price, and the name of the month in which it occurred.
Display the highest average price of the year, along with the week number for that price, and the name of the month in which it occurred.
Display the average gas price for each month. (To get the average price for a given month, calculate the average of the average weekly prices for that month.)*/
There's a lot more to this than just finding the average. Let's go through the assignment's details sentence by sentence:
Display the lowest average price of the year, along with the week number for that price, and the name of the month in which it occurred.
So you need to find the minimum value and the week number that it occurs. So it might be best to read all the data. You could put it into a vector or array - that way the week number is just index+1
"and the name of the month". That means you must parse the date field and you need a function or array to convert a month number to its name. Jumping ahead, you only need to remember the month number. You can throw away the rest of the date.
Display the highest average price of the year, along with the week number for that price, and the name of the month in which it occurred.
That's almost identical to the requirement above.
Display the average gas price for each month. (To get the average price for a given month, calculate the average of the average weekly prices for that month.)
So you need another pass through the data to compute the monthly average.
struct Prices {
int monthNo;
double price;
bool read(istream &is);
};
void showMonthlyAverages(vector<Prices> &data)
{
if (data.size() == 0) return;
int month = data[0].monthNo;
unsigned count=0;
double sum = 0.0;
for (unsigned i=0; i<data.size(); ++i) {
if (data[i].monthNo != month) {
// New month. Print the data for the last month
cout << month << '\t' << sum/count << '\n';
sum = count = 0;
month = data[i].monthNo;
}
sum += data[i].price;
++count;
}
// Now print the last one
cout << month << '\t' << sum/count << '\n';
}