Question

*** USING C++ ***

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// C++ program to read the input file and calculate the MPG for each car and calculate and display the total miles driven, total gallons used and average MPG for all cars
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
ifstream fin("car_readings.txt"); // open the input file, provide full path to file
int carNumber, milesDriven, gallonsUsed;
double mpg, total_miles_driven = 0, total_gallons_used = 0, avg_mpg = 0;
int numCars=0;
// if file can be opened
if(fin.is_open())
{
cout<<left<<setw(15)<<"Car Number"<<left<<setw(15)<<"Miles Driven"<<left<<setw(15)<<"Gallons Used"<<left<<setw(10)<<"MPG"<<endl;
cout<<fixed<<setprecision(2);
// read till the end of file
while(!fin.eof())
{
fin>>carNumber>>milesDriven>>gallonsUsed;
// calculate mpg
if(gallonsUsed > 0)
mpg = ((double)milesDriven)/gallonsUsed;
else
mpg = 0;
// add mpg to avg_mpg, milesdriven to total_miles_driven, gallonsUsed to total_gallons_used
avg_mpg += mpg;
total_miles_driven += milesDriven;
total_gallons_used += gallonsUsed;
numCars++; // increment number of cars
cout<<left<<setw(15)<<carNumber<<left<<setw(15)<<milesDriven<<left<<setw(15)<<gallonsUsed<<left<<setw(10)<<mpg<<endl;
}

fin.close(); // close the input file
// calculate average mpg
avg_mpg = avg_mpg/numCars;
// display summary data
cout<<endl<<"Total miles driven : "<<total_miles_driven<<endl;
cout<<"Total gallons used: "<<total_gallons_used<<endl;
cout<<"Average miles per gallon for all cars: "<<avg_mpg<<endl;
}else
cout<<"Unable to open file : car_readings.txt"<<endl;

return 0;
}
//end of program

Output:

Input file:

Values in a line must be separated by a single space or tab

Format of a line in the file : <car number><space><miles driven><space><gallons used>

25 1500 65 36 3540 138 | 44 1889 65 52 2466 115 68 2265 8

Output:

Car Number 25 Gallons Used 65 138 36 Miles Driven 1500 3540 1889 2466 2265 MPG 23.08 25.65 29.06 21.44 26.03 44 65 52 115 68

Add a comment
Know the answer?
Add Answer to:
*** USING C++ *** Create a file containing the following: car numbers, miles driven, and gallons...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT