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 <bits/stdc++.h>
using namespace std;
class car {
public :
string carCompany;
int costOfCar;
int numberOfAirbags;
car(string CarCompany, int CostOfcar, int NumberOfAirbags) {
carCompany = CarCompany;
costOfCar = CostOfcar;
numberOfAirbags = NumberOfAirbags;
}
};
int main() {
int n;
cout << "Total number of cars \n";
cin >> n;
vector<car> objs;
for (int i=0; i<n; i++) {
string carCompany;
int costOfCar;
int numberOfAirbags;
cout << "Enter car Company name :- ";
cin >> carCompany;
cout << "Enter cost of car :- ";
cin >> costOfCar;
cout << "Enter number of airbags in car :- ";
cin >> numberOfAirbags;
objs.push_back(car(carCompany,costOfCar,numberOfAirbags));
}
// Writing array of objects in 'cars.txt' file
ofstream MyFile("cars.txt");
for (int i=0; i<n; i++) {
MyFile << objs[i].carCompany << " " << objs[i].costOfCar << " " << objs[i].numberOfAirbags << endl;
}
// Search the data by carcompany from 'cars.txt'
string searchCarCompany = "";
cout << "Enter the car company name to search :- " ;
cin >> searchCarCompany;
cout << "Details of cars:- " << endl;
ifstream CarsFile("cars.txt");
while ( !CarsFile.eof() ) {
string carCompany;
int costOfCar;
int numberOfAirbags;
CarsFile >> carCompany >> costOfCar >> numberOfAirbags; // Reading data from file
if(carCompany == searchCarCompany) { // Matching car company name from file with input name
cout << carCompany << " " << costOfCar << " " << numberOfAirbags << endl; // printing car details
}
}
return 0 ;
}
Comments
Leave a comment