file I/0 math and while loops

closed account (2EURX9L8)
I want to read from a file with the day of the week, high temp and low temp.
like this:
friday 25.5 11
saturday 36.4 -2


and want to report to the screen the number of days in the file, the high temp avg and the low temp avg

and this is the code I have so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
double highTemp, lowTemp, lowAvg, highAvg;
	int count=0, freezDays;
	string dayOfweek;

	ifstream fin("weather.txt");
	
	if(!fin) {
		cout<<"Error opening file. Shutting down....\n";
		return 0;}
	while(fin>>dayOfweek)
	{
		fin>>highTemp;
		fin>>lowTemp;
		count++;
		highTemp+=highTemp;
		lowTemp+=lowTemp;
		
	}
	
	if(count !=0) {
		highAvg = highTemp/static_cast<double>(count);
		lowAvg=lowTemp/static_cast<double>(count);
		cout<<"The average high tempeture was "<<highAvg<<endl;
		cout<<"The average low tempeture was "<<lowAvg<<endl;
	}


It is reporting pretty wrong, any guidance?


basically I want to read and add every high temp then / it by the number of high temps, same thing with the low temps
Last edited on
closed account (2EURX9L8)
any help would be greatly appreciated.
During every iteration, you are reading a new highTemp and then doubling it in line 15. This is likely not your intent. Try this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
double highTemp, lowTemp, lowAvg = 0, highAvg = 0; //Initialize these two
	int count=0, freezDays;
	string dayOfweek;

	ifstream fin("weather.txt");
	
	if(!fin) {
		cout<<"Error opening file. Shutting down....\n";
		return 0;}
	while(fin>>dayOfweek)
	{
		fin>>highTemp;
		fin>>lowTemp;
		count++;
		highAvg+=highTemp; // highAvg is a running total of all highTemps to date
		lowAvg+=lowTemp;
		
	}
	
	if(count !=0) {
		highAvg /= static_cast<double>(count); // Now divide it by count to actually make it an average.
		lowAvg/= static_cast<double>(count);
		cout<<"The average high tempeture was "<<highAvg<<endl;
		cout<<"The average low tempeture was "<<lowAvg<<endl;
	}

closed account (2EURX9L8)
Thanks a lot, that cleared things up a bit.






Last edited on
Topic archived. No new replies allowed.