Lab7 2

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

#include <iostream>

#include <fstream>
#include<iomanip>

using namespace std;


enum{end,nBrand=50, nNumber=20, nOwner=50,choiceShow_file=1,choiceA,ChoiceB,};

struct Car {
char brand[nBrand+1];
char numberPlate[nNumber+1];
char ownerLastName[nOwner+1];
void input_data();
void output_data();
};

void displayCarData(const char* targetBrand, Car cars[], int carsCount) {


cout << "Cars of brand " << targetBrand << ":" << endl;
bool isBrand = false;
for (int i = 0; i < carsCount; ++i) {
int j = 0;

if (strcmp(cars[i].brand,targetBrand)==0) {
cars[i].output_data(); isBrand = true;
}
}

int main() {
char fname[] = "bin.txt";
ofstream outputFile("cars_data.txt", ios::app);
ofstream outFile_bin(fname,ios::binary|ios::app);
if (!outputFile.is_open()) {
cerr << "Unable to open file!" << endl;
return 1;
}

int numOfCarsToAdd;
cout << "Enter the number of cars you want to add: ";
cin >> numOfCarsToAdd;

Car newCar;

for (int i = 0; i < numOfCarsToAdd; ++i) {

newCar.input_data();

outputFile << newCar.brand << " " << newCar.numberPlate << " " <<
newCar.ownerLastName << endl;
outFile_bin.write((char*)&newCar,sizeof(Car));
}

outputFile.close();

cout << "Car data successfully written to the file." << endl;
ifstream inputFile("cars_data.txt");

if (!inputFile.is_open()) {
cerr << "Unable to open file!" << endl;
return 1;
}

const int maxCars = 100;


Car cars[maxCars];
int carsCount = 0;

while (inputFile >> cars[carsCount].brand >> cars[carsCount].numberPlate >>


cars[carsCount].ownerLastName) {
carsCount++;
if (carsCount >= maxCars) {
cerr << "Maximum number of cars reached. Processing stopped." <<
endl;
break;
}
}

inputFile.close();

cout << "Number of cars of each brand:" << endl;


for (int i = 0; i < carsCount; ++i) {
int count = 1;
if (cars[i].brand[0] != '\0') {
for (int j = i + 1; j < carsCount; ++j) {
int k = 0;
while (cars[i].brand[k] != '\0' && cars[j].brand[k] != '\0'
&& cars[i].brand[k] == cars[j].brand[k]) {
k++;
}
if (cars[i].brand[k] == '\0' && cars[j].brand[k] == '\0') {
count++;
cars[j].brand[0] = '\0';
}
}
cout << "Brand: " << cars[i].brand << ", Count: " << count <<
endl;
}
}

char targetBrand[50];
cout << "Enter car brand to display information: ";
cin >> targetBrand;
displayCarData(targetBrand, cars, carsCount);

system("pause");
return 0;
}

void Car::input_data()
{
cout << "Enter car brand: ";
cin .getline(brand,nBrand);
cout << "Enter car number plate: ";
cin .getline(numberPlate,nNumber);
cout << "Enter owner's last name: ";
cin.getline(ownerLastName,nOwner);
}

void Car::output_data()
{
cout << setw(nBrand) << brand << setw(nNumber) << numberPlate << setw(nOwner)
<< ownerLastName << endl;
}

You might also like