Answer to Question #180575 in C++ for Gaurav Kumar

Question #180575

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


1
Expert's answer
2021-04-12T13:26:21-0400
#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 ;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS