Create a class named as car with
data members as
carcompany,cost of car,number
of airbags. Create a file and write
the array of objects into file.
Search the data by carcompany
from the stored file and display
the result .
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Car
{
private:
string carCompany;
float costCar;
int numberAirbags;
public:
Car(){}
Car(string carCompany,float costCar,int numberAirbags){
this->carCompany=carCompany;
this->costCar=costCar;
this->numberAirbags=numberAirbags;
}
string getCarCompany(){
return this->carCompany;
}
float getCostCar(){
return this->costCar;
}
int getNumberAirbags(){
return this->numberAirbags;
}
};
int main()
{
const string FILE_NAME="Cars.txt";
//Creating an array of objects of class Car
Car cars[5];
cars[0]=Car("Audi",25000,4);
cars[1]=Car("Ford",15000,2);
cars[2]=Car("BMW",25400,2);
cars[3]=Car("Honda",45604,4);
cars[4]=Car("Fiat",14556,4);
//write the array of objects into file.
ofstream carsOfstream(FILE_NAME, ios::out);
for(int i=0; i<5; ++i){
carsOfstream <<cars[i].getCarCompany() << " "<<cars[i].getCostCar()<< " "<< cars[i].getNumberAirbags()<< "\n";
}
carsOfstream.close();
//read
ifstream carsIfstream(FILE_NAME);
if(!carsIfstream)
{
cerr << "Error: open file '"<<FILE_NAME<<"' for reading\n";
return 1;
}
string carCompany;
float costCar;
int numberAirbags;
int counter=0;
string line;
//read from file
while(carsIfstream>>carCompany>>costCar>>numberAirbags){
cars[counter]=Car(carCompany,costCar,numberAirbags);
counter++;
}
carsIfstream.close();
//Search the data by carcompany from the stored file and display the result.
string carcompanyTarget;
int numbeOfCar=0;
cout<<"Enter car company: ";
getline(cin,carcompanyTarget);
for(int i=0;i<5;i++)
{
if(cars[i].getCarCompany()==carcompanyTarget){
cout <<"Car company: "<<cars[i].getCarCompany() << ", Cost car: "<<cars[i].getCostCar()<< ", Number of airbags: "<< cars[i].getNumberAirbags()<< "\n";
numbeOfCar++;
}
}
if(numbeOfCar==0){
cout<<"\nNot found\n\n";
}
system("pause");
return 0;
}
Comments
Leave a comment