I have a base class and a derived class. Currently, I am reading each file separately i.e. the carfile and the sportsCarFile. They are then loaded as members to be used for other purposes. I am trying to get my head around how I would read one single file and then read each line in the file correctly calling the correct load function. Below is a table of what the data would look like:
Car/SportsCar CarName Age Colour Price
Car Abbort 8 Yellow 899.99
SportsCar Aufdi 7 Brown 989.99
Car ATX 5 White 9823.23
Car POL 3 Yellow 8232.33
And here is the current code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Car{
public:
Car();
virtual void Load(ifstream& carFile);
virtual int LoadString(string filename);
void display();
protected:
string CarName;
int Age;
string Colour;
double Price;
int countCars;
Car *ptrToCarList;
};
class SportsCar : public Car
{
public:
SportsCar();
virtual void LoadSports(ifstream& carFile);
virtual int LoadString(string filename);
void displayLoad();
void display();
protected:
int engineSize;
SportsCar *ptrToSportsCarList;
int countCars;
};
Car::Car()
{
CarName = "Unknown";
countCars = 0;
}
void Car::Load(ifstream& carFile)
{
carFile >> CarName >> Age >> Colour >> Price;
}
int Car::LoadString(string filename)
{
ifstream inFile(filename);
if (!inFile)
{
cout << "Sorry, file not found" << endl;
return -1;
}
ptrToCarList = new Car[countCars];
for (int i = 0; i < countCars; i++)
{
ptrToCarList[i].Load(inFile);
}
inFile.close();
return 0;
}
void Car::display()
{
cout << CarName << " " << Age << " " << Colour << " " << Price << " " ;
}
void SportsCar::displayLoad()
{
Car::display();
cout<<engineSize<<endl;
}
void SportsCar::display()
{
for (int i = 0; i < countCars; i++)
{
ptrToSportsCarList[i].displayLoad();
}
}
void SportsCar::LoadSports(ifstream& carFile){
Car::Load( carFile);
carFile >> engineSize;
}
SportsCar::SportsCar()
{
CarName = "Unknown";
countCars = 0;
}
int SportsCar::LoadString(string filename)
{
ifstream inFile(filename);
if (!inFile)
{
cout << "Sorry, file not found" << endl;
return -1;
}
countCars = 2;
ptrToSportsCarList = new SportsCar[countCars];
for (int i = 0; i < countCars; i++)
{
ptrToSportsCarList[i].LoadSports(inFile);
}
inFile.close();
return 0;
}
int main()
{
SportsCar example2;
example2.LoadString("sportsCarFile.txt");
example2.display();
return 0;
}