WSQ 16

Link to github: https://github.com/carlosgreen/TC1017/blob/master/cars.cpp

This program needs to read a file which has a data base with various information relevant to cars. By reading the information, the program needs to print out the follow data:

  • average gas mileage in city (City MPG)
  • average gas mileage on highway (Highway MPG)
  • average midrange price of the vehicles in the set.

The program opens the file and then uses a string variable in order to read stuff from the subline (substring aka substr).

Also, the program has a if inside a loop, which permits the file to be read several times until getting the average midrange price of a vehicle. 

Here is how the code should look:

<iostream>

<fstream>

<sstream>

<cstdlib>

<string>

 

using namespace std;

int cars(string carstext){

  string range, city, highway;

  int counter=0;

  float range2=0.0, city2=0.0, highway2=0.0, sumcity=0.0, sumrange=0.0, sumhigh=0.0;

  ifstream cars;

  string line;

  cars.open(carstext.c_str());

  while(getline(cars, line)){

    if((counter%2)==0){

      range=line.substr(42, 47);

      range2=atoi(range.c_str());

 

      city=line.substr(53, 54);

      city2=atoi(city.c_str());

 

      highway=line.substr(56, 57);

      highway2=atoi(highway.c_str());

 

      sumrange=sumrange + range2;

      sumcity=sumcity + city2;

      sumhigh=sumhigh + highway2;

 

    counter++;

  }

  }

  cout<<“city mileage: “<<sumcity/93<<endl;

  cout<<“highway mileage: “<<sumhigh/93<<endl;

  cout<<“midrange vehicle price: “<<sumrange/93<<endl;

}

int main(){

  cout<<cars(“93cars.txt”);

 

}

 

CC BY 4.0 WSQ 16 by carlos green is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.