Store the following data in a file named Data3. txt 54 250 19 62 525 38 71 123 6
ID: 3777132 • Letter: S
Question
Store the following data in a file named Data3. txt 54 250 19 62 525 38 71 123 6 85 1322 86 97 235 14 Each line contains a taxi ID, the miles driven and the gallons of gas used. Write a complete C++ program which reads the data from the file you created in part anc displays on the screen the taxi ID, miles driven, gallons of gas used and miles per gallon (mp for each car. The output should also display the total miles driven, total gallons of gas used and the average mpg for all taxis. These totals should be displayed at the end of the output report. Given the data in part a), your program should produce the following output to the screen.Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
//To display data as per the format
void disp(string id, int m, int g, int mp)
{
cout<<id<<" "<<m<<" "<<g<<" "<<mp<<endl;
}
int main()
{
//ifstream object to read file
ifstream myfile;
//Open the specified file
myfile.open("Data3.txt");
string line;
string id;
int miles, gas, mpg, tmiles = 0, tgas = 0, tmpg = 0, c = 0;
//Displays the Heading
cout<<"ID Miles Gas MPG ";
//Checks file can be opened or not
if (myfile.is_open())
{
//Reads till end of file
while (!myfile.eof())
{
//Extract data from file
myfile>>id;
myfile>>miles;
myfile>>gas;
//Calculation
mpg = miles/gas;
tmiles += miles;
tgas += gas;
tmpg += mpg;
disp(id, miles, gas, mpg);
c++; //Counter for number of records
}
myfile.close();
}
else
cout<<"Error: In open file";
cout<<" Total miles driven "<<tmiles<<endl;
cout<<" Total gallons used "<<tgas<<endl;
cout<<" Total MPG "<<(double)tmpg/c;
}
Output:
ID Miles Gas MPG
54 250 19 13
62 525 38 13
71 123 6 20
85 1322 86 15
97 235 14 16
Total miles driven 2455
Total gallons used 163
Total MPG 15.4