Reading numbers from a file, adding them / averaging them
Hi all,
I'm working on a problem from a textbook to practice working with data files. I'm a beginner programmer who is in an introductory class so bear with me here.
Firstly, the data file I'm working with looks like this:
54 250 19
62 525 38
71 123 6
85 1332 86
97 235 14
Those are supposed to be in 3 columns and the columns have titles.. you'll see when you look at the output I get:
Code:
Car No. Miles Driven Gallons Used
54 250 19
62 525 38
71 123 6
85 1332 86
97 235 14
The total miles driven is 235
The total gallons of gas used is 14
The average miles per gallon of gas used is 16
Aaanyway, I can read the file just fine and output it as shown. My problem is that it only prints out the last number in each column when I'm trying to sum or average it.
Here's what I'm SUPPOSED to do:
1. Total number of miles driven for all cars
2. Total gallons of gas used for all cars
3. Average mpg
As you can see, it's just printing the last number in the list instead of actually summing anything. And the average just goes off of 235 / 14. How can I fix this? :C Thanks in advance, I've been doing this problem for a couple of hours now and it's frustrating.
My code so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int car, miles, gas;
int sumMiles = 0;
int sumGas = 0;
int avgMPG = 0;
FILE *inFile;
inFile = fopen("cars.dat", "r");
if (inFile == NULL)
{
printf("\nFailed to open file.\n");
exit(1);
}
printf("\nCar No. Miles Driven Gallons Used\n");
while (fscanf(inFile, "%d %d %d",&car, &miles, &gas) != EOF)
printf("%-7d %-15d %d\n",car,miles,gas);
sumMiles += miles;
sumGas += gas;
avgMPG = sumMiles / sumGas;
printf("\nThe total miles driven is %d\n", sumMiles);
printf("The total gallons of gas used is %d\n", sumGas);
printf("The average miles per gallon of gas used is %d\n", avgMPG);
fclose(inFile);
return 0;
}