Opening a file and using a structure

I am pretty dang stumped on this question.....


Create a file containing the following: car numbers, miles driven, and gallons of gas used
in each car (do not include the readings):

Car Number Miles Driven Gallons Used
25 1500 65
36 3540 138
44 1889 65
52 2466 115
68 2265 87

Write a program that reads the data in the file and displays the car number, miles driven,
gallons used and the miles per gallon for each car. The output should also contain the
total miles drive, total gallons used, and average miles per gallon for all the cars. These
totals should be displayed at the end of the output report.


..... I know I need to use a structure and I pretty much wrote a rough nonfunctional code but now I'm pretty lost as to how to take separate parts of a file and alter/use it in a way that will actually help me solve a problem.
Any help would be appreciated.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
struct cars
{
	int carnum;
	int miles;
	int gals;
};
int main()
{
ifstream file;
cars car[100]; 
double totalmiles = 0;
double totalgals = 0;
file.open("Carinfo.cpp");
    if(file.fail())
    {
        cout << "File was not opened. " << endl;
        system("pause");
        return 0;
    }
    while(file.good())
    {
      file>>car[100].carnum;
	  file>>car[100].gals;
	  file>>car[100].miles;
	  for (int i; i<100; i++)
	  {
		  totalmiles = totalmiles + car[i].miles;
                  totalgals = totalgals + car[i].gals;
       
	  }
    }
cout <<"Total mile driven by all cars is " << totalmiles << endl;
cout <<"Total gallons used by all cars is " << totalgals << endl;
cout <<"Average miles per gallons by all cars is " << totalmiles/totalgals << endl;
system("pause");
return 0;
}
use a for loop to read all the values in
1
2
3
4
5
for (int i=0;i<3;i++)
{
in_file>>car[i].carnum>>car[i].miles>>car[i].gals;

right after the while(file.good()) ?
Topic archived. No new replies allowed.