I can't seem to find the problem in my code whether it be to me being sick or blind I'm unsure of. The error I get is:
unresolved external symbol"struct MonthlyBudget_cdecl actual(void)" (?actual##YA?AUMonthlyBudget##XZ) referenced in function_main.
Any help would be appreciated.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
struct MonthlyBudget {
double housing;
double utilities;
double householdExpenses;
double transportation;
double food;
double medical;
double insurance;
double entertainment;
double clothing;
double misc;
MonthlyBudget(double housingCost, double utilitiesCost, double householdExpensesCost, double transportationCost, double foodCost,
double medicalCost, double insuranceCost, double entertainmentCost, double clothingCost, double miscCost) {
housing = housingCost;
utilities = utilitiesCost;
householdExpenses = householdExpensesCost;
transportation = transportationCost;
food = foodCost;
medical = medicalCost;
insurance = insuranceCost;
entertainment = entertainmentCost;
clothing = clothingCost;
misc = miscCost;
}
MonthlyBudget() {
housing = 0;
utilities = 0;
householdExpenses = 0;
transportation = 0;
food = 0;
medical = 0;
insurance = 0;
entertainment = 0;
clothing = 0;
misc = 0;
}
void setHousing(double housingCost) {
housing = housingCost;
}
double getHousing() {
return housing;
}
void setUtilities(double utilitiesCost) {
utilities = utilitiesCost;
}
double getUtilities() {
return utilities;
}
void setHouseholdExpenses(double householdEXCost) {
householdExpenses = householdEXCost;
}
double getHouseholdExpenses() {
return householdExpenses;
}
void setTransportation(double transportationCost) {
transportation = transportationCost;
}
double getTransportation() {
return transportation;
}
void setFood(double foodCost) {
food = foodCost;
}
double getFood() {
return food;
}
void setMedical(double medicalCost) {
medical = medicalCost;
}
double getMedical() {
return medical;
}
void setInsurance(double insuranceCost) {
insurance = insuranceCost;
}
double getInsurance() {
return insurance;
}
void setEntertainment(double entertainmentCost) {
entertainment = entertainmentCost;
}
double getEntertainment() {
return entertainment;
}
void setClothing(double clothingCost) {
clothing = clothingCost;
}
double getClothing() {
return clothing;
}
void setMisc(double miscCost) {
misc = miscCost;
}
double getMisc() {
return misc;
}
};
int main() {
MonthlyBudget budget(500, 150, 65, 50, 250, 30, 100, 150, 75, 50);
MonthlyBudget actual();
double housing, utilities, householdExpenses, transportation, food, medical, insurance, entertainment, clothing, misc;
cout << "How much did you spend on housing?" << endl;
do {
cin >> housing;
actual().setHousing(housing);
} while (housing < 0);
cout << "How much did you spend on utilities?" << endl;
do {
cin >> utilities;
actual().setUtilities(utilities);
} while (utilities < 0);
cout << "How much did you spend on household expenses?" << endl;
do {
cin >> householdExpenses;
actual().setHousing(householdExpenses);
} while (householdExpenses < 0);
cout << "How much did you spend on transportation?" << endl;
do {
cin >> transportation;
actual().setTransportation(transportation);
} while (transportation < 0);
cout << "How much did you spend on food?" << endl;
do {
cin >> food;
actual().setFood(food);
} while (food < 0);
cout << "How much did you spend on medical?" << endl;
do {
cin >> medical;
actual().setMedical(medical);
} while (medical < 0);
cout << "How much did you spend on insurance?" << endl;
do {
cin >> insurance;
actual().setInsurance(insurance);
} while (insurance < 0);
cout << "How much did you spend on entertainment?" << endl;
do {
cin >> entertainment;
actual().setEntertainment(entertainment);
} while (entertainment < 0);
cout << "How much did you spend on clothing?" << endl;
do {
cin >> clothing;
actual().setClothing(clothing);
} while (clothing < 0);
cout << "How much did you spend on misc?" << endl;
do {
cin >> misc;
actual().setMisc(misc);
} while (misc < 0);
cout << "Showing projected budget compared to actual:" << endl;
cout << "Housing: " << budget.housing - actual().housing << endl;
cout << "Utilities: " << budget.utilities - actual().utilities << endl;
cout << "Household Expenses: " << budget.householdExpenses - actual().householdExpenses << endl;
cout << "Transportation: " << budget.transportation - actual().transportation << endl;
cout << "Food: " << budget.food - actual().food << endl;
cout << "Medical: " << budget.medical - actual().medical << endl;
cout << "Insurance: " << budget.insurance - actual().insurance << endl;
cout << "Entertainment: " << budget.entertainment - actual().entertainment << endl;
cout << "Clothing: " << budget.clothing - actual().clothing << endl;
cout << "Misc: " << budget.misc - actual().misc << endl;
string input;
cin >> input;
return 0;
}//main()
Again thanks for any help! I know the code is pretty messy and there are better ways to do this, but for the life of me I can't think of anything with my flu right now.
Removed () from actual() and all mentions. Fixed the program.
Related
i know the question looks confusing but truthfully it isn't like it seems.
im building a programme about drone ( sorry if it doesnt make sense)
Here from this code i get error "(line 116 )identifier "camrecord" is undefined " and "Compiler Error C2065
'(line 116) identifier' : undeclared identifier" although i already identify and declare them? how to solve this?
thank you
#include<iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
#include <string.h>
using namespace std;
void manualMode();
void defaultMode();
void Getdata(double & camrecord, double & Projectframerate);
void calculate(double & camrecord, double & Projectframerate, double & actualframerate);
int speed, timeTofly, operation;
int angle = 90;
int main() {
int mode = 0, part = 3;
double flyLevel;
int obstacleSensor = 0, timer = 3, AccelerometerSensor = 0, tempSensor = 25;
char startPause;
cout << "Drone Flying Technology" << endl;
do {
cout << "Choose Mode: (1)Default, (2)Manual \n";
cin >> mode;
if (mode == 1)
defaultMode();
if (mode == 2)
manualMode();
} while (mode == 0);
cout << "Choose how to fly: (1)Upper , (2)Lower , (3)Upper and Lower \n";
cin >> part;
switch (part) {
case 1:
case 2:
flyLevel = 0.5;
break;
case 3:
flyLevel = 1;
break;
}
if (obstacleSensor == 0) {
do {
cout << "Press (S) to Start,and swing the propeller." << endl;
cin >> startPause;
cout << "LED is On\n";
while (AccelerometerSensor != flyLevel) {
AccelerometerSensor++;
}
cout << "Flying session Started! Time Left:" << timeTofly << endl;
cout << "Eagle eye Operation Started!\n";
timeTofly = timeTofly / 2;
cout << "Crusing mode initiate Time Left:" << timeTofly << endl;
timeTofly = timeTofly / 2;
cout << "Free fly commenced Time Left:" << timeTofly << endl;
timeTofly = 0;
startPause = 'P';
} while ((startPause == 's') || (startPause == 'S'));
}
cout << "End!\nLED is Off";
return 0;
}
void manualMode() {
cout << "Enter drone speed (knot) \n";
cin >> speed;
cout << "Enter Time to fly: \n";
cin >> timeTofly;
cout << "Choose Operation: (1)Fully manual, (2)Normal Orientation, (3)Free orientation, (4)FPV racing, (5)All\n";
cin >> operation;
}
void defaultMode() {
int howtofly;
cout << "how to fly: (1)Circle, (2)Altitude Hold, (3)Free orientation";
cin >> howtofly;
switch (howtofly) {
case 1:
speed = 30;
timeTofly = 3;
break;
case 2:
speed = 40;
timeTofly = 3;
break;
case 3:
speed = 60;
timeTofly = 3;
break;
}
char name[25];
char id[5];
float m1, m2, m3, m4, m5;
ofstream outputFile("droneinfo.txt", ios::out);
cout << "Please enter object you want to record,drone id imei number and your 5 preferred video fps:\n";
cout << "\nPress <ctrl> + z to stop. \n";
while (cin >> id >> name >> m1 >> m2 >> m3 >> m4 >> m5)
{
outputFile << id << " " << name << " " << m1 << " " << m2 << " " << m3 << " " << m4 << " " << m5 << endl;
}
double fps = 0.0;
double Projectframerate = 0.0;
double actualframerate, out = 0;
Getdata(camrecord, Projectframerate);
calculate(camrecord, Projectframerate, actualframerate);
cout << "The actual frame rate is =" << actualframerate << " f/s\n";
}
void Getdata(double& camrecord, double& Projectframerate) {
cin >> camrecord;
cin >> Projectframerate;
cout << "Please enter\n Recording frame rate =" << camrecord << "f/s ,\ndesired frame rate="
<< Projectframerate << "f/s\n";
}
//-------------------//
void calculate(double& camrecord, double& Projectframerate, double& actualframerate) {
actualframerate = camrecord / Projectframerate;
}
//-------------------//
So a reference as an argument is used when you want to input a variable and modify it. Looking at void Getdata(double& camrecord, double& Projectframerate), you are saying that Getdata takes a camrecord and a projectframe rate, reads these value and modifies them, so that the caller can use the new values.
Looking at the code, it does not seem Getdata is actually reading the input values. So there is an inconsistency.
To be consistent with the implementation of the method, the method Getdata should not take any arguments - but only return them. Now, you cannot return two arguments, but you can pack them into a struct and return that:
struct Data
{
double camrecord;
double Projectframerate;
};
Data Getdata();
The definition of Getdata can then be:
Data getData()
{
Data data;
cin >> data.camrecord;
cin >> data.Projectframerate;
cout << "Please enter\n Recording frame rate =" << data.camrecord << "f/s ,\ndesired frame rate="
<< data.Projectframerate << "f/s\n";
return data;
}
Similarly can be done for calculate.
I'm unsure why when more than one transaction has been made the FOR LOOP won't iterate through the vector of "buyers". Am I missing something simple? I've spent the last few hours trying to fix this but to no avail. If any one could possibly help with my problem I'd be eternally grateful.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cctype>
using namespace std;
//This class is for the car details that the user can purchase.
class cCar {
private:
string _sName;
double _dPrice;
public:
cCar(string s, double d)
{
_sName = s;
_dPrice = d;
}
string getName() { return _sName; }
double getPrice() { return _dPrice; }
};
//This is where all the car detail purchases are created and stored in the object 'carlist'
vector<cCar> CarDatabase(vector<cCar>& car_list)
{
car_list.push_back(cCar("Blue Nissan Skyline", 1000));
car_list.push_back(cCar("Red Mini", 3000));
car_list.push_back(cCar("Black Land Rover", 4000));
car_list.push_back(cCar("Beatle", 9000));
car_list.push_back(cCar("Ferrari", 300000));
return car_list;
}
//This class stores the user's transactions
class Finance {
private:
string _sUserName;
double _dCostOfCar;
string _sChosenCar;
int _iFinancePlan;
double _dDepositedAmount;
double _dMonthlyPayments;
double _dTotalLeftToPay;
public:
Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay)
{
_sUserName = sName;
_dCostOfCar = dCostOfCar;
_sChosenCar = sChosenCar;
_iFinancePlan = iFinancePlan;
_dDepositedAmount = dDepositedAmount;
_dMonthlyPayments = dDMonthlyPayments;
_dTotalLeftToPay = dTotalLeftToPay;
}
string getUserName() { return _sUserName; }
double getdCostOfCar() { return _dCostOfCar; }
string getChosenCar() { return _sChosenCar; }
int getFinancePlan() { return _iFinancePlan; }
double getDepositAmount() { return _dDepositedAmount; }
double getMonthlyAmount() { return _dMonthlyPayments; }
double getTotalLeftToPay() { return _dTotalLeftToPay; }
};
//1. This displays the car menu items.
void display_menu(vector<cCar>& car_list)
{
cout << "\nMENU";
for (int iCount = 0; iCount != car_list.size(); iCount++) {
cout << "\n" << iCount + 1 << ". " << car_list[iCount].getName();
cout << "\n\tPrice: £" << car_list[iCount].getPrice();
cout << "\n";
}
}
//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.
void selectedCar(vector<cCar>& car_list, string& sNameOfChosenCar, double& dCostOfChosenCar)
{
int iSelectionFromMenu = -1;
do {
cout << "\nChoose a car that you'd wish to buy from the menu (1 - " << car_list.size() << "): ";
cin >> iSelectionFromMenu;
if (iSelectionFromMenu > 0 && iSelectionFromMenu <= car_list.size()) {
sNameOfChosenCar = car_list[iSelectionFromMenu - 1].getName();
dCostOfChosenCar = car_list[iSelectionFromMenu - 1].getPrice();
}
else {
cout << "\nPlease enter valid number!";
iSelectionFromMenu = -1;
}
} while (iSelectionFromMenu == -1);
}
//This procedure gets from the user their preferred finance plan through their input.
void FinanceLength(int& iFinanceLength)
{
do {
cout << "\nHow long do you wish for your finance plan to last? (1 - 4 years): ";
cin >> iFinanceLength;
if (iFinanceLength < 0 || iFinanceLength > 4) {
cout << "\nOops, try again! Please enter between 1 - 4!";
}
} while (iFinanceLength < 0 || iFinanceLength > 4);
}
//This procedure gets the user's deposit.
void DepositMoney(double& dDepositAmount)
{
do {
cout << "\nEnter deposit amount (minimum £500 accepted): £";
cin >> dDepositAmount;
if (dDepositAmount < 500) {
cout << "\nTry again! Deposit an amount greater than or equal to £500.";
}
} while (dDepositAmount < 500);
}
//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%
double TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)
{
double dChargePercentage = 0.10;
double dTotalLeftToPay = dCostOfChosenCar + (dCostOfChosenCar * dChargePercentage) - dDepositAmount + 135;
return dTotalLeftToPay;
}
//This calculates monthly payments.
double MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)
{
double dMonthlyPayments = (dTotalLeftToPay / iFinanceLength) / 12;
return dMonthlyPayments;
}
//This asks the user whether they'd like to restart the application.
void RestartOptions(char& cOption, bool& bExit)
{
do {
cout << "\nDo you wish to make another purchase? (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
switch (cOption) {
case 'Y':
bExit = false;
break;
case 'N':
bExit = true;
break;
default:
cout << "Sorry, that's an invalid input, please try again!";
continue;
}
} while (cOption != 'y' && cOption != 'Y' && cOption != 'n' && cOption != 'N');
}
//This string function returns either year or years (plural)
string YearOrYears(int iFinanceLength)
{
return (iFinanceLength > 1) ? "years" : "year";
}
//This displays receipt of the user's transaction.
//HERE IS WHRERE I "M STRUGGLING TO ITERATE
void Receipt(const string& sUserName, const int& iFinanceLength, const double& dDepositAmount, char cOption, bool& bExit, const string& sNameOfChosenCar, const double& dCostOfChosenCar, vector<Finance>& buyers)
{
double dTotalLeftToPay = TotalLeftToPay(iFinanceLength, dDepositAmount, dCostOfChosenCar);
double dMonthlyPayments = MonthlyPayments(dTotalLeftToPay, iFinanceLength);
buyers.push_back(Finance(sUserName, dCostOfChosenCar, sNameOfChosenCar, iFinanceLength, dDepositAmount, dMonthlyPayments, dTotalLeftToPay));
for (int iCount = 0; iCount != buyers.size(); iCount++) {
cout << "\nReceipt for: " << buyers[iCount].getUserName() << ". ";
cout << "\nYou have chosen " << buyers[iCount].getChosenCar() << ".";
cout << "\nYour finance plan timescale is " << buyers[iCount].getFinancePlan() << " " << YearOrYears(iFinanceLength) << ".";
cout << "\nYou've deposited £" << buyers[iCount].getDepositAmount() << ".";
cout << "\nTotal left to pay: £" << buyers[iCount].getTotalLeftToPay();
cout << "\nMonthly Payments: £" << buyers[iCount].getMonthlyAmount();
cout << "\n";
}
RestartOptions(cOption, bExit);
}
//This asks the user whether they're happy with the options of they've chosen.
void AcceptDeclineOptions(string& sUserName, int& iFinanceLength, double& dDepositAmount, bool& bExit, string& sNameOfChosenCar, double& dCostOfChosenCar, vector<Finance> buyers)
{
char cOption = 0;
do {
cout << "\nConfirm finance plan (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
if (cOption == 'Y' || cOption == 'N') {
if (cOption == 'Y') {
Receipt(sUserName, iFinanceLength, dDepositAmount, cOption, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}
else {
RestartOptions(cOption, bExit);
}
}
else {
cout << "\nSorry, that's not a valid command.";
}
} while (cOption != 'Y' && cOption != 'N');
}
int main()
{
bool bExit = false;
int iFinanceLength = 0;
double dDepositAmount = 0;
string sNameOfChosenCar = "";
double dCostOfChosenCar = 0;
vector<cCar> car_list;
CarDatabase(car_list);
vector<cCar> car_purchases;
vector<Finance> buyers;
do {
cout << "Welcome!";
string sUserName = "";
cout << "\nEnter your name: ";
cin >> sUserName;
display_menu(car_list);
selectedCar(car_list, sNameOfChosenCar, dCostOfChosenCar);
FinanceLength(iFinanceLength);
DepositMoney(dDepositAmount);
AcceptDeclineOptions(sUserName, iFinanceLength, dDepositAmount, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
} while (bExit == false);
}
I'm doing a project where we need to create a basic Zoo Tycoon game, in which we create a base class called Animal, 3 derived classes of Animal: Tiger, Penguin, Turtle. We also need to create a Zoo class that holds 3 separate arrays for each animal. I've written up my code but keep getting segmentation faults when compiling. I believe this is due to the way I create my object arrays as well as the method I use for inserting objects into them. I've uploaded my entire code. I apologize for the length. I didn't know what segment I could have uploaded to give a clear idea of what I'm doing.
This is my code
Animal.h
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal
{
private:
int age;
double cost;
int numberOfBabies;
double baseFoodCost;
double payoff;
public:
Animal();
Animal(int, double, int, double, double);
int getAge();
void setAge(int);
double getCost();
void setCost(double);
int getNumberOfBabies();
void setNumberOfBabies(int);
double getBaseFoodCost();
void setBaseFoodCost(double);
double getPayoff();
void setPayoff(double);
};
#endif
Animal.cpp
#include "Animal.h"
Animal::Animal(int a, double c, int n, double b, double p)
{
age = a;
cost = c;
numberOfBabies = n;
baseFoodCost = b;
payoff = p;
}
int Animal::getAge()
{
return age;
}
void Animal::setAge(int a)
{
age = a;
}
double Animal::getCost()
{
return cost;
}
void Animal::setCost(double c)
{
cost = c;
}
int Animal::getNumberOfBabies()
{
return numberOfBabies;
}
void Animal::setNumberOfBabies(int n)
{
numberOfBabies = n;
}
double Animal::getBaseFoodCost()
{
return baseFoodCost;
}
void Animal::setBaseFoodCost(double b)
{
baseFoodCost = b;
}
double Animal::getPayoff()
{
return payoff;
}
void Animal::setPayoff(double p)
{
payoff = p;
}
Tiger.h
#ifndef TIGER_H
#define TIGER_H
#include "Animal.h"
class Tiger: public Animal
{
public:
Tiger();
Tiger(int, double, int, double, double);
};
#endif // !TIGER_H
Tiger.cpp
#include "Tiger.h"
Tiger::Tiger(int age, double cost, int numberOfBabies, double baseFoodCost, double payoff) : Animal(age, cost, numberOfBabies, baseFoodCost, payoff)
{
}
Penguin.h
#ifndef PENGUIN_H
#define PENGUIN_H
#include "Animal.h"
class Penguin: public Animal
{
public:
Penguin();
Penguin(int, double, int, double, double);
};
#endif
Penguin.cpp
#include "Penguin.h"
Penguin::Penguin(int age, double cost, int numberOfBabies, double baseFoodCost, double payoff) : Animal(age, cost, numberOfBabies, baseFoodCost, payoff)
{
}
Turtle.h
#ifndef TURTLE_H
#define TURTLE_H
#include "Animal.h"
class Turtle: public Animal
{
public:
Turtle();
Turtle(int, double, int, double, double);
};
#endif
Turtle.cpp
#include "Turtle.h"
Turtle::Turtle(int age, double cost, int numberOfBabies, double baseFoodCost, double payoff) : Animal(age, cost, numberOfBabies, baseFoodCost, payoff)
{
}
Zoo.h
#ifndef ZOO_H
#define ZOO_H
#include "Animal.h"
#include "Tiger.h"
#include "Penguin.h"
#include "Turtle.h"
#include <cstdlib>
#include <iostream>
using namespace std;
class Zoo
{
private:
Tiger **arrayTiger;
Penguin **arrayPenguin;
Turtle **arrayTurtle;
int sizeTiger, sizePenguin, sizeTurtle;
int capacityTiger, capacityPenguin, capacityTurtle;
double amount;
double revenue;
public:
Zoo();
Zoo(double);
void insertTiger(Tiger);
void insertPenguin(Penguin);
void insertTurtle(Turtle);
void Events();
double getAmount();
void setAmount(double);
void subtractAmount(double);
Tiger** getTigerArray();
Penguin** getPenguinArray();
Turtle** getTurtleArray();
void calculateRevenue();
double getRevenue();
void incrementAge();
void resetRevenue();
};
#endif
Zoo.cpp
#include "Zoo.h"
Zoo::Zoo(double a)
{
amount = a;
capacityTiger = 10;
capacityPenguin = 10;
capacityTurtle = 10;
sizeTiger = 0;
sizePenguin = 0;
sizeTurtle = 0;
revenue = 0;
arrayTiger = new Tiger*[capacityTiger];
arrayPenguin = new Penguin*[capacityPenguin];
arrayTurtle = new Turtle*[capacityTurtle];
}
void Zoo::insertTiger(Tiger t)
{
if (sizeTiger < capacityTiger)
{
arrayTiger[sizeTiger++] = &t;
}
else
{
int oldTigerCapacity = capacityTiger;
capacityTiger *= 2;
Tiger** newArrayTiger = new Tiger* [capacityTiger];
for (int i = 0; i < oldTigerCapacity; i++)
{
newArrayTiger[i] = arrayTiger[i];
}
delete[] arrayTiger;
arrayTiger = newArrayTiger;
arrayTiger[sizeTiger++] = &t;
}
}
void Zoo::insertPenguin(Penguin p)
{
if (sizePenguin < capacityPenguin)
{
arrayPenguin[sizePenguin++] = &p;
}
else
{
int oldPenguinCapacity = capacityPenguin;
capacityPenguin *= 2;
Penguin** newArrayPenguin = new Penguin* [capacityPenguin];
for (int i = 0; i < oldPenguinCapacity; i++)
{
newArrayPenguin[i] = arrayPenguin[i];
}
delete[] arrayPenguin;
arrayPenguin = newArrayPenguin;
arrayPenguin[sizePenguin++] = &p;
}
}
void Zoo::insertTurtle(Turtle turt)
{
if (sizeTurtle < capacityTurtle)
{
arrayTurtle[sizeTurtle++] = &turt;
}
else
{
int oldTurtleCapacity = capacityTurtle;
capacityTurtle *= 2;
Turtle** newArrayTurtle = new Turtle* [capacityTurtle];
for (int i = 0; i < oldTurtleCapacity; i++)
{
newArrayTurtle[i] = arrayTurtle[i];
}
delete[] arrayTurtle;
arrayTurtle = newArrayTurtle;
arrayTurtle[sizeTurtle++] = &turt;
}
}
void Zoo::subtractAmount(double a)
{
amount -= a;
}
double Zoo::getAmount()
{
return amount;
}
void Zoo::setAmount(double a)
{
amount += a;
}
void Zoo::Events()
{
int option = 0;
option = rand() % 4 + 1;
switch(option)
{
case 1: cout << "\n\nA sickness has occurred at the zoo." << endl << endl;
break;
case 2: cout << "\n\nThere has been a boom in zoo attendance." << endl << endl;
break;
case 3: cout << "\n\nA baby animal is born." << endl << endl;
break;
case 4: cout << "\n\nNothing happens." << endl << endl;
break;
}
}
Tiger** Zoo::getTigerArray()
{
return arrayTiger;
}
Penguin** Zoo::getPenguinArray()
{
return arrayPenguin;
}
Turtle** Zoo::getTurtleArray()
{
return arrayTurtle;
}
void Zoo::incrementAge()
{
for(int i = 0; i < sizeTiger; i++)
{
if((arrayTiger[i]->getCost()) == 10000)
{
arrayTiger[i]->setAge((arrayTiger[i]->getAge()) + 1);
}
}
for(int i = 0; i < sizePenguin; i++)
{
if((arrayPenguin[i]->getCost()) == 1000)
{
arrayPenguin[i]->setAge((arrayPenguin[i]->getAge()) + 1);
}
}
for(int i = 0; i < sizeTurtle; i++)
{
if((arrayTurtle[i]->getCost()) == 100)
{
arrayTurtle[i]->setAge((arrayTurtle[i]->getAge()) + 1);
}
}
}
void Zoo::calculateRevenue()
{
for (int i = 0; i < sizeTiger; i++)
{
revenue += (arrayTiger[i]->getPayoff());
}
for (int i = 0; i < sizePenguin; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
for (int i = 0; i < sizeTurtle; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
}
double Zoo::getRevenue()
{
return revenue;
}
void Zoo::resetRevenue()
{
revenue = 0;
}
main.cpp
#include "Animal.h"
#include "Penguin.h"
#include "Tiger.h"
#include "Turtle.h"
#include "Zoo.h"
#include <iostream>
using namespace std;
int main()
{
const int baseFeedingCost = 10;
Zoo z1(100000);
bool playGame = false;
bool menuExit = false;
char userStart, continueGame, loopPurchase, loopChoice = ' ';
int day = 0;
int initializer = 0;
cout << "\nWelcome to Zoo Tycoon!\n\nIn this game you will manage a zoo business." << endl;
while(!menuExit)
{
cout << "\nA: Play Game" << endl;
cout << "B: Exit" << endl;
cout << "\n\nPlease Select an option: ";
cin.get(userStart);
cin.ignore(INT_MAX, '\n');
if(userStart == 'A' || userStart == 'a') //user selected to start game
{
playGame = true;
menuExit = true;
cout << "\n\nYou will start with $" << z1.getAmount() << " in the bank." << endl;
cout << "\n\nTo begin your Zoo, you must purchase three types of animals (tigers, penguins, turtles)";
cout <<"\nin quantities of either 1 or 2." << endl << endl;
cout << "Please enter you desired number of tigers (1 or 2): ";
cin >> initializer;
if (initializer == 2)
{
Tiger t1(0, 10000, 1, 50, 2000);
z1.insertTiger(t1);
z1.subtractAmount(10000);
Tiger t2(0, 10000, 1, 50, 2000);
z1.insertTiger(t2);
z1.subtractAmount(10000);
cout << "\n\nYou will start with 2 tigers." << endl;
}
else if (initializer == 1)
{
Tiger t1(0, 10000, 1, 50, 2000);
z1.insertTiger(t1);
z1.subtractAmount(10000);
cout << "\nYou will start with 1 tiger." << endl;
}
cout << "\n\nPlease enter you desired number of penguins (1 or 2): ";
cin >> initializer;
if (initializer == 2)
{
Penguin p1(0, 1000, 5, 10, 100);
z1.insertPenguin(p1);
z1.subtractAmount(1000);
Penguin p2(0, 1000, 5, 10, 100);
z1.insertPenguin(p2);
z1.subtractAmount(1000);
cout << "\n\nYou will start with 2 penguins." << endl;
}
else if (initializer == 1)
{
Penguin p1(0, 1000, 5, 10, 100);
z1.insertPenguin(p1);
z1.subtractAmount(1000);
cout << "\n\nYou will start with 1 penguin." << endl;
}
cout << "\n\nPlease enter you desired number of turtles (1 or 2): ";
cin >> initializer;
if (initializer == 2)
{
Turtle tr1(0, 100, 10, 5, 5);
z1.insertTurtle(tr1);
z1.subtractAmount(100);
Turtle tr2(0, 100, 10, 5, 5);
z1.insertTurtle(tr2);
z1.subtractAmount(100);
cout << "\n\nYou will start with 2 turtles." << endl << endl;
}
else if (initializer == 1)
{
Turtle tr1(0, 100, 10, 5, 5);
z1.insertTurtle(tr1);
z1.subtractAmount(100);
cout << "\n\nYou will start with 1 turtle." << endl << endl;
}
cin.ignore(255, '\n');
cin.clear();
}
else if(userStart == 'B' || userStart == 'b')
{
cout << "\nThis game will now exit." << endl << endl;
menuExit = true;
}
else //user inputted invalid response
{
cout << "\n\nI'm sorry but your response is invalid. Please try again." << endl;
cin.ignore(255, '\n');
cin.clear();
}
}
while(playGame) //daily turns that ends when user enters false for playGame
{
loopChoice = loopPurchase = ' ';
z1.incrementAge();
cout << "\n\nDay: " << ++day << endl;
cout << "\nYou have $" << z1.getAmount() << " in the bank";
z1.Events();
cout << "\n\nWould you like to purchase an adult animal? ";
cin.get(loopPurchase);
cin.ignore(INT_MAX, '\n');
if(loopPurchase == 'Y' || loopPurchase == 'y')
{
cout << "\n\nA: Tiger" << endl;
cout << "B: Penguin" << endl;
cout << "C: Turtle" << endl;
cout << "\nPlease choose from the animals listed above: ";
cin.get(loopChoice);
cin.ignore(INT_MAX, '\n');
if(loopChoice == 'A' || loopChoice == 'a')
{
cout << "\n\nYou have chosen to purchase a Tiger" << endl;
Tiger tLoop(3, 10000, 1, 50, 2000);
z1.insertTiger(tLoop);
z1.subtractAmount(10000);
}
else if(loopChoice == 'B' || loopChoice == 'b')
{
cout << "\n\nYou have chosen to purchase a Penguin" << endl;
Penguin pLoop(3, 1000, 5, 10, 100);
z1.insertPenguin(pLoop);
z1.subtractAmount(1000);
}
else if(loopChoice == 'C' || loopChoice == 'c')
{
cout << "\n\nYou have chosen to purchase a Turtle" << endl;
Turtle trLoop(3, 100, 10, 5, 5);
z1.insertTurtle(trLoop);
z1.subtractAmount(100);
}
}
z1.calculateRevenue();
cout << "\n\nYour daily revenue is $" << z1.getRevenue();
//z1.setAmount((z1.getAmount()) + (z1.getProfit()));
z1.resetRevenue();
cout << "\n\nEnd of Day: " << day << ". Would you like to continue? (Enter yes or no): ";
cin.get(continueGame);
cin.ignore(INT_MAX, '\n');
if (continueGame == 'y' || continueGame == 'Y')
{
cout << "\nGame will continue. Proceeding to next day." << endl << endl;
}
else
{
cout << "\n\nYou have chosen to quit the game. Game will now exit." << endl << endl;
playGame = false;
}
}
return 0;
}
The code is huge. I have not reviewed everything.
In Zoo, you define your Animal arrays as:
Tiger **arrayTiger;
Penguin **arrayPenguin;
Turtle **arrayTurtle;
I don't know why a double pointer. Just *arrayTiger, etc. would work. You must also change the Insert method. Instead of assigning &t, just use t.
There are other improvements to make.
In Zoo, the insertTiger (etc), should also subtract amount. You always subtract the amount after calling insert, and you already know the price.
Your wrote almost the same code 3 times for the three animals when initializing arrays of animals. You could check if the input is 1 or 2 (to validate) and then insert animals in a for loop.
Finally. You are not reusing almost anything. You have a lot of repeated code for tigers, turtles and penguins.
Your code is too big as mentioned in the previous answer because of which I couldn't go through the entire code, but the segmentation fault you encounter could be because of the following piece of code :
void Zoo::calculateRevenue()
{
for (int i = 0; i < sizeTiger; i++)
{
revenue += (arrayTiger[i]->getPayoff());
}
for (int i = 0; i < sizePenguin; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
for (int i = 0; i < sizeTurtle; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
}
If you see here, in the third "for loop", you run the loop till sizeTurtle but are using the arrayPenguin for it. I think this is a mistake and what you wanted to do was something of this sort :
for (int i = 0; i < sizeTurtle; i++)
{
revenue += (arrayTurtle[i]->getPayoff());
}
That being said, they're could be other problems in the code that i am not aware of, but this certainly seems like a candidate to cause a crash in the program.
I don't understand why my code is not calculating the birthrate and the deathrate. I keep on getting 0 for both. I included the static_cast<double> to ensure this wouldn't happen. Any feedback / help?
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
int getBirths()
{
return birthrate;
}
int getDeaths()
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
void calculateBirthRate(PopInfo);
void calculateDeathRate(PopInfo);
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
void PopInfo::calculateBirthRate(PopInfo newCity)
{
double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
You accidentally made birthrate and deathrate as local variables. Remove the leading keyword double, to make it:
void PopInfo::calculateBirthRate(PopInfo newCity)
{
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
Even so, it's kind of strange that you're passing newCity by value – did you mean to store the rates back in the same object, as in:
void PopInfo::calculateBirthRate(PopInfo& newCity)
{
newCity.birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo& newCity)
{
newCity.deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
or did you mean to operate on the object in-place, as in:
void PopInfo::calculateBirthRate()
{
birthrate = static_cast<double>(bir) / citpop;
}
void PopInfo::calculateDeathRate()
{
deathrate = static_cast<double>(dea) / citpop;
}
I don't think you ever call the functions that calculate birth rate and death rate! That is on top of the issues already identified, but I'm pretty sure it matters... Put a cout debug statement in there and see if I'm right...
Another problem: since "rate" is a number between zero and 1, and your function getBirths returns an int, you are going to run into a rounding problem...
Also not sure you ever set dea and bir in the context of the class (you declare them at the main level). So many places where you are inviting problems...
The easiest solution would be to rewrite these two functions:
double getBirths()
{
return (double)numberOfBirths/citypop;
}
double getDeaths()
{
return (double)numberOfDeaths/citypop;
}
But read your code, and ask yourself what the scope of your variables is, where they are set (and if you ever set them...), where they are used, where you perform type conversions.... You can learn a lot from that.
EDIT
I couldn't help myself, and decided to copy your program and debug it. After a few simplifications in the structure I came up with the following (note I moved the two functions calculateBirthRate and calculateDeathRate inside the class definition for consistency; and I used the "internally known" variables totalCityPopulation etc, rather than some of the "alternative" ones you were using... it was getting very confusing. Finally, as I mentioned in the original answer - I made sure the birth and death rates were actually calculated. I have marked changed lines with //*** :
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
double getBirths() //*** was int
{
return birthrate;
}
double getDeaths() //*** was int
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
//*** this function moved into the class definition
void calculateBirthRate()
{
birthrate = (double)numberOfBirths/totalCityPopulation; //*** using different variables
}
//*** this function moved into the class definition
void calculateDeathRate()
{
deathrate = (double)numberOfDeaths / totalCityPopulation; //*** using different variables
}
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
newCity.calculateBirthRate(); //*** added, or it's never calculated
newCity.calculateDeathRate(); //*** added, or it's never calculated
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
When I run this code, I get the following:
What is the city name?:
Amsterdam
What is the total city population?:
1234567
What are the number of births?:
12345
What are the number of deaths?:
54321
The city name is Amsterdam
The total city population is 1234567
The birth rate is 0.00999946
The death rate is 0.044
The diff between your code and mine is:
33c33
< double getBirths()
---
> int getBirths()
38c38
< double getDeaths()
---
> int getDeaths()
68,71c68,69
< void calculateBirthRate()
< {
< birthrate = (double)numberOfBirths/totalCityPopulation;
< }
---
> void calculateBirthRate(PopInfo);
> void calculateDeathRate(PopInfo);
73,76d70
< void calculateDeathRate()
< {
< deathrate = (double)numberOfDeaths / totalCityPopulation;
< }
117,118d110
< newCity.calculateBirthRate();
< newCity.calculateDeathRate();
129a122,125
> void PopInfo::calculateBirthRate(PopInfo newCity)
> {
> double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
> }
130a127,130
> void PopInfo::calculateDeathRate(PopInfo newCity)
> {
> double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
> }
double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
Here you are driving two new variable names birthrate and death rate. You're not writing the values two the class data members. Writing the type before the names overwrites it. To change, simply remove it.
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
I think I am having trouble with binary file io. If I run my program, create some employee objects and then display them everything works fine. If I save the object data and reload the program I get an RTTI exception. It apears to me that my LoadEmployeeData() and Savelist(vector &e) functions work just fine. The exception occurs in my DisplayEmployeeData() function when I try to use typeid.
Just to reiterate, I am getting an RTTI error when using typeid on an object loaded from disk.
//****************header file***********
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <typeinfo>
#include <ctime>
#include <cstdlib>
using namespace std;
class Employee
{
private:
int employeeID;
char name[80];
int SSN;
public:
Employee();
Employee(int, char*,int);
virtual ~Employee();
virtual void DisplayBaseData();
//getters
int GetID();
char* getName();
int GetSSN();
//setters
void SetID(int);
void SetName(char*);
void SetSSN(int);
};//end Employee class
class Salary : public Employee
{
private:
double salary;
public:
Salary();
Salary(int, char*, int, double); //id, name, ssn, salary
~Salary();
void DisplayEmployeeData();
//getters
double GetSalary();
//setters
void SetSalary(double);
};//end class Exempt
class Hourly : public Employee
{
private:
double rate;
double hoursWorked;
public:
Hourly();
Hourly(int, char*, int, double, double); //id, name, ssn, rate
~Hourly();
void DisplayEmployeeData();
//getters
double GetRate();
double GetHoursWorked();
//setters
void SetRate(double);
void SetHoursWorked(double);
};//end Hourly Class
const int HOURLYTYPE = 0;
const int SALARYTYPE = 1;
//*******body*******
#include "lab05.h";
Employee::Employee(){};
Employee::Employee(int ID, char* nme, int ssn) : employeeID(ID), SSN(ssn)
{
strcpy(name, nme);
}
int Employee::GetID()
{
return employeeID;
}
char* Employee::getName()
{
return name;
}
int Employee::GetSSN()
{
return SSN;
}
void Employee::SetID(int i)
{
employeeID = i;
}
void Employee::SetName(char* n)
{
strcpy(name, n);
}
void Employee::SetSSN(int i)
{
SSN = i;
}
void Employee::DisplayBaseData()
{
cout << "ID: \t" << employeeID << endl;
cout << "Name: \t " << name << endl;
cout << "SSN: \t" << SSN << endl;
}
Employee::~Employee(){}
Salary::Salary(){}
Salary::Salary(int id, char* nme, int ssn, double slry) : Employee(id, nme, ssn), salary(slry){}
void Salary::DisplayEmployeeData()
{
DisplayBaseData();
cout << "Salary: \t " << salary << endl;
}
double Salary::GetSalary()
{
return salary;
}
void Salary::SetSalary(double d)
{
salary = d;
}
Salary::~Salary(){}
Hourly::Hourly(){}
Hourly::Hourly(int id, char* nme, int ssn, double rte, double worked) : Employee(id, nme, ssn), rate(rte), hoursWorked(worked){}
void Hourly::DisplayEmployeeData()
{
DisplayBaseData();
cout << "Rate: \t" << rate << endl;
cout << "Worked: \t " << hoursWorked << endl;
}
double Hourly::GetRate()
{
return rate;
}
double Hourly::GetHoursWorked()
{
return hoursWorked;
}
void Hourly::SetRate(double d)
{
rate = d;
}
void Hourly::SetHoursWorked(double d)
{
hoursWorked = d;
}
Hourly::~Hourly(){}
vector<Employee*> LoadEmployeeData()
{
vector<Employee*> employeeList;
string fileName = "";
cout << "\nEnter filename for employee data: ";
cin >> fileName;
fstream file;
file.open(fileName, ios::in, ios::binary);
char buffer[4096] = {0};
int numEntries;
file.read((char*)&numEntries, sizeof(int));
cout << numEntries << " number of entries found." << endl;
if (numEntries != 0)
{
int identifier;
for (int i = 0; i < numEntries; i++)
{
file.read((char*)&identifier, sizeof(int));
if (identifier == SALARYTYPE)
{
Employee* temp = new Salary();
file.read((char*)temp, sizeof(Salary));
employeeList.push_back(temp);
}
else if (identifier == HOURLYTYPE)
{
Employee* temp = new Hourly();
file.read((char*)temp, sizeof(Hourly));
employeeList.push_back(temp);
}
}
}
else cout << "No Entries found." << endl;
file.close();
return employeeList;
}//end LoadEmployeeData function
void ListEmployees(vector<Employee*> &e)
{
if (e.size() != 0)
{
for (int i = 0; i < e.size(); i++)
{
if (typeid(*(e[i])) == typeid(Hourly))
{
cout << "\n(" << i << ")" << endl;
dynamic_cast<Hourly*>(e[i])->DisplayEmployeeData();
}
else if (typeid(*(e[i])) == typeid(Salary))
{
cout << "\n(" << i << ")" << endl;
dynamic_cast<Salary*>(e[i])->DisplayEmployeeData();
}
}
}
else cout << "No items in list" << endl;
}// end ListEmployees function
void ModifyEmployee(vector<Employee*> &e)
{
cout << "Enter employee selection." << endl;
}
void CreateEmployee(vector<Employee*> &e)
{
bool continueLoop = true;
srand(time(0)); //seed random number generator
cout << "\n Enter new employee information." << endl;
cout << "Name: ";
char newName[80] = {0};
cin >> newName;
cout << "\n SSN: ";
int newSSN;
cin >> newSSN;
char newType = '-1';
do
{
cout << "\n Is new employee paid a (s)alary or (h)ourly rate? ";
cin >> newType;
if (newType == 's' || newType == 'h') continueLoop = false;
else cout << "incorrect input" << endl;
}while (continueLoop == true);
if (newType == 's')
{
cout << "Enter salary amount: ";
double amount;
cin >> amount;
e.push_back(new Salary(rand() % 1000 + 1, newName, newSSN, amount));
}
else if (newType == 'h')
{
cout << "Enter hourly amount: ";
double amount;
cin >> amount;
cout << "Enter hours worked: ";
double hoursWorked;
cin >> hoursWorked;
e.push_back(new Hourly(rand() % 1000 + 1, newName, newSSN, amount, hoursWorked));
}
}
void Savelist(vector<Employee*> &e)
{
if (e.size() == 0)
cout << "No employees in list. Nothing done." << endl;
else
{
cout << "Enter save filename: ";
char fileName[80] = {'\0'};
cin >> fileName;
fstream* file = new fstream();
file->open(fileName, ios::out, ios::binary);
char buffer[80] = {'\0'};
int numEntries = e.size();
file->write((char*)&numEntries, sizeof(int)); //writes number of entries
for (int i = 0; i < e.size(); i++)
{
if (typeid(*e[i]) == typeid(Salary))
{
int classType = SALARYTYPE;
file->write((char*)&classType, sizeof(int));
file->write((char*)dynamic_cast<Salary*>(e[i]), sizeof(Salary));
}
else if (typeid(*e[i]) == typeid(Hourly))
{
int classType = HOURLYTYPE;
file->write((char*)&classType, sizeof(int));
file->write((char*)dynamic_cast<Hourly*>(e[i]), sizeof(Salary));
}
}
file->close();
}
}
void DeleteEmployee(vector<Employee*> &e)
{
cout << "Input index number of employee to delete: ";
int idx = 0;
cin >> idx;
if (idx > e.size() -1)
cout << "invalid index number\n" << endl;
else
{
delete e[idx];
e.erase(e.begin() + idx); //removes from list
}
}
int main()
{
const int ZERO = 0;
const int ONE = 1;
const int TWO = 2;
const int THREE = 3;
const int FOUR = 4;
const int FIVE = 5;
const int SIX = 6;
int exitMainLoop = false; //for flow control
int mainMenuChoice = -1;
vector<Employee*> employeeList;
do
{
cout << "Select from the following options." << endl;
cout << "(1) Load employee data file." << endl;
cout << "(2) View Employees." << endl;
cout << "(3) Modify Employee data. " << endl;
cout << "(4) Create new employee." << endl;
cout << "(5) Save list to file." << endl;
cout << "(6) Delete employee data. " << endl;
cout << "(0) Exit program." << endl;
//add more options
cout << "Enter selection: ";
cin >> mainMenuChoice;
if (cin.fail())
{
cout << "\nInvalid selection. Try again" << endl;
cin.clear();
string garbage = "";
cin >> garbage;
}
else if (mainMenuChoice == ONE)
employeeList = LoadEmployeeData();
else if (mainMenuChoice == TWO)
ListEmployees(employeeList);
else if (mainMenuChoice == THREE)
ModifyEmployee(employeeList);
else if (mainMenuChoice == FOUR)
CreateEmployee(employeeList);
else if (mainMenuChoice == FIVE)
Savelist(employeeList);
else if (mainMenuChoice == SIX)
DeleteEmployee(employeeList);
else if (mainMenuChoice == ZERO)
exitMainLoop = true;
}while(exitMainLoop == false);
system("PAUSE");
}
You can't read/write raw C++ objects from/to disk if they have virtual methods (or use RTTI, which requires virtual methods) because there's no guarantee that the vtable address from the first execution will be written to disk, and there's no guarantee that the vtable will be in the same place the next time the program is run -- hence, the address that was written to disk will point somewhere incorrect when it is read back.
file->write((char*)dynamic_cast<Hourly*>(e[i]), sizeof(Salary));
looks suspicious. did you mean sizeof(Hourly)?