#include<iostream>
#include<string>
using namespace std;
class Product
{
public:
int static BarCode;
int Quantity;
double Price;
friend class ProudectQueue;
friend class ProductNode;
friend class Customerr;
friend class customerQueue;
//public:
product() {
BarCode= 0, Quantity = 0, Price = 0;
}
product(int barCode, int Quantity, double price)
{
BarCode=barCode ,Quantity=Quantity , Price = price;
}
void DisplayList();
void setBarCode(int bc)
{BarCode=bc;}
int getBarCode()
{return BarCode;}
void setQuantity(int Q)
{Quantity=Q;}
int getQuantity()
{return Quantity;}
void setPrice(int r)
{Price=r;}
int getPrice()
{return Price;}
void printProductDetails()
{ cout<<getBarCode()<<"\n";
cout<<getQuantity()<<"\n";
cout<<getPrice()<<endl;
}
};
class ProductNode //class node
{
public:
Product data;
ProductNode* next;
ProductNode()
{
data.BarCode = 0, data.Quantity = 0, data.Price = 0;
}
ProductNode(int BarCode, int Quantity, double price)
{
data.BarCode = BarCode, data.Quantity=Quantity, data.Price = price;
}
};
class ProductQueue {
ProductNode* rear, * front;
int counter;
public:
ProductQueue() { rear = front = NULL; counter = 0; }
~ProductQueue() { Product Productdata; while (!isempty()) dequeue(Productdata); }
bool isempty() { if (counter == 0) return true; else return false; }
void enqueue(Product ProductData) {
ProductNode* newnode = new ProductNode;
newnode->data = ProductData;
if (isempty())
{
rear = newnode;
front = newnode;
}
else {
rear->next = newnode;
rear = newnode;
}
counter++;
}
bool dequeue(Product& data)
{
if (isempty()) { cout << "Error:the queue is empty\n"; return false; }
else {
ProductNode* nextnode;
nextnode = front->next;
data = front->data;
delete front;
front = nextnode;
counter--;
return true;
}
}
int find(char ProductName)
{
ProductNode* currNode = front;
int position = 1;
while (currNode->data.BarCode!= ProductName)
{
if (currNode != NULL)
currNode = currNode->next;
position++;
}
if (currNode) return position;
return -1;
}
void display()
{
cout << endl;
cout << "Front-->";
ProductNode* currNode = front;
for (int i = 0; i < counter; i++)
{
if (i == 0) cout << "\t";
else cout << "\t\t";
cout << "Product BarCode: " << currNode->data.BarCode << "\t"
<< "Product Quantity: " << currNode->data.Quantity<< "\t"
<< "Product price : " << currNode->data.Price;
if (i != counter - 1) cout << endl;
else cout << "\t<-- Rear" << endl;
currNode = currNode->next;
}
}
bool modify()
{
if(isempty())
{
cout << "Error ,the queue is empty \n"; return false;
}
else
{
int BarCode1;
double Price1;
int Quantity1;
cout << "\nEnter BarCode : "; cin >> BarCode1;
cout << "\nEnter price : "; cin >> Price1;
cout << "\nEnter Quantity : "; cin >> Quantity1;
rear->data.BarCode = BarCode1;
rear->data.Price = Price1;
rear->data.Quantity = Quantity1;
return true;
}
}
};
class Seller //seller class
{
private:
string Name;
int ID, contact;
float Reating;
friend class SellerQueue;
friend class SellerNode;
public:
Seller() { Name = "unknown", ID= 0, contact = 0,Reating=0; }
Seller(string name, int id, int con,float reating) { Name = name, ID=id , contact = con,Reating=reating; }
void setName(string name) { Name = name; }
void setID(int id) { ID = id; }
void setcontact(int con) { contact = con; }
void setReating(float reating){Reating=reating;}
string getName() { return Name; }
int getID() { return ID; }
int getcontact() { return contact; }
float getReating(){ return Reating;}
void printSellerInfo()
{
cout << "\tName : " << Name << "\t";
cout << "\tSeller ID : " << ID << "\t";
cout << "\tcontact: " << contact<< "\t\n";
cout << "\tSeller Reating : " << Reating << "\t";
}
};
class SellerNode
{
public:
Seller Data;
SellerNode* Next;
SellerNode() { Data.Name = "unknown", Data.ID = 0, Data.contact= 0,Data.Reating=0; }
SellerNode(string name, int id, int con,float reating)
{ Data.Name = name, Data.ID = id, Data.contact=con ,Data.Reating=reating;}
};
class SellerQueue {
SellerNode* rear, * front;
int counter;
public:
SellerQueue() { rear = front = NULL; counter = 0; }
~SellerQueue() { Seller Sellerdata; while (!isempty()) dequeue(Sellerdata); }
bool isempty() { if (counter == 0) return true; else return false; }
void enqueue(Seller SellerData) {
SellerNode* newnode = new SellerNode;
newnode->Data = SellerData;
if (isempty())
{
rear = newnode;
front = newnode;
}
else {
rear->Next = newnode;
rear = newnode;
}
counter++;
}
bool dequeue(Seller& data)
{
if (isempty()) { cout << "Error:the queue is empty\n"; return false; }
else {
SellerNode* nextnode;
nextnode = front->Next;
data = front->Data;
delete front;
front = nextnode;
counter--;
return true;
}
}
int find(int SellerID)
{
SellerNode* currNode = front;
int position = 1;
while (currNode->Data.ID != SellerID)
{
if (currNode != NULL)
currNode = currNode->Next;
position++;
}
if (currNode) return position;
return -1;
}
void display()
{
cout << endl;
cout << "Front-->";
SellerNode* currNode = front;
for (int i = 0; i < counter; i++)
{
if (i == 0) cout << "\t";
else cout << "\t\t";
cout << "Seller name : " << currNode->Data.Name << "\t" <<
"Seller ID:" << currNode->Data.ID << "\t"
<< "contact:" << currNode->Data.contact<<"\t"<<
"Seller Reating"<<currNode->Data.Reating;
if (i != counter - 1) cout << endl;
else cout << "\t<-- Rear" << endl;
currNode = currNode->Next;
}
}
bool modify()
{
if (isempty())
{
cout << "Error ,the queue is empty \n"; return false;
}
else
{
string name1;
int ID1;
int contact1;
float Reating1;
cout << "\nEnter seller name : "; cin >> name1;
cout << "\nEnter Seller ID : "; cin >> ID1;
cout << "\nEnter contact : "; cin >> contact1;
cout << "\nEnter seller Reating: "; cin >> Reating1;
rear->Data.Name = name1;
rear->Data.ID = ID1;
rear->Data.contact = contact1;
rear->Data.Reating = Reating1;
return true;
}
}
};
class Customer //custmer class
{
public:
int ID;
string Name;
float Point;
int Phone;
friend class Product;
friend class customerQueue;
friend class customerrNode;
Customer() {
ID = 0; Name = "Unknown"; Point = 0;Phone=0;
}
Customer(unsigned int id, string name, float point,int phone) {
ID = id; Name = name; Point = point; Phone=phone;
}
void setID(unsigned int id) { ID = id; }
void setName(string name) { Name = name; }
void setPoint(float point) { Point= point; }
void setPhone(int phone){ Phone= phone; }
void setProductforCustomer(int B, int q, double pr)
{
Product.getBarCode() = B;
Product.getQuantity() = q;
Product.getPrice() = pr; // erorr
}
int getBarCode() { return Product.BarCode; }
int Quantity() { return Product.Quantity; }
double getPrice() { return Product.Price; }
unsigned int getID() { return ID; }
string getName() { return Name; }
float getPoint() { return Point; }
int getPhone(){ return Phone; }
void printCustomerInfo()
{
cout << "\tID number : " << ID << "\t";
cout << "\tCustomer Name : " << Name << "\t";
cout << "\tPoint is : " << Point << "\t";
cout<<"\tphone Number is :"<< Phone<<"\t";
cout << "\tBarCode" << Product.BarCode;
cout << "\tQuantity"<<Product.Quantity;
cout << "\tprice : "<<Product.Price << endl;
}
};
class customerNode
{
public:
customerNode* Next;
Customer Data;
customerNode()
{
Data.ID = 0, Data.BarCode = 0, Data.Name = "unkown";
}
customerNode(int id, string Name, int BarCode)
{
Data.ID = id, Data.BarCode = BarCode, Data.Name = Name; //error
}
};
class customerQueue {
customerNode* rear, * front;
int counter;
public:
customerQueue() { rear = front = NULL; counter = 0; }
~customerQueue() { Customer customerdata; while (!isempty()) dequeue(customerdata); }
bool isempty() { if (counter == 0) return true; else return false; }
void enqueue(Customer customerdata) {
customerNode* newnode = new customerNode;
newnode->Data = customerdata;
if (isempty())
{
rear = newnode;
front = newnode;
}
else {
rear->Next = newnode;
rear = newnode;
}
counter++;
}
bool dequeue(Customer& data)
{
if (isempty()) { cout << "Error:the queue is empty\n"; return false; }
else {
customerrNode* nextnode; //error
nextnode = front->Next;
data = front->Data;
delete front;
front = nextnode;
counter--;
return true;
}
}
int find(int id)
{
customerNode* CurrNode = front;
int position = 1;
while (CurrNode->Data.ID != id)
{
if (CurrNode != NULL)
CurrNode = CurrNode->Next;
position++;
}
if (CurrNode) return position;
return -1;
}
void display()
{
cout << endl;
cout << "Front-->";
customerNode* currNode = front;
for (int i = 0; i < counter; i++)
{
if (i == 0) cout << "\t";
else cout << "\t ";
cout << "Customer ID : " << currNode->Data.ID << " Custmer Name :"
<< currNode->Data.Name <<
" Custmer point: " << currNode->Data.Point<<
" Prouduct BarCode: " << currNode->Data.Product.BarCode <<
" Product Quantity :" << currNode->Data.Product.Quantity<<
" product price : " << currNode->Data.Product.Price;
if (i != counter - 1) cout << endl;
else cout << "\t<-- Rear" << endl;
currNode = currNode->Next;
}
}
bool modify()
{
if (isempty())
{
cout << "Error ,the queue is empty \n"; return false;
}
else
{
int BarCode1;
int Quantity1;
double Price1;
unsigned int ID1;
string Name1;
cout << "\nEnter customer ID : "; cin >> ID1;
cout << "\nEnter customer Name : "; cin >> Name1;
cout << "\nEnter BarCode : "; cin >> BarCode1;
cout << "\nEnter Quantity : "; cin >>Quantity1;
cout << "\nEnter price : "; cin >> Price1;
rear->Data.Product.BarCode = BarCode1;
rear->Data.Product.Quantity = Quantity;
rear->Data.Product.Price = Price1;
return true;
}
}
};
class Action
{
int product,Time;
string Seller, Customer;
double E_bidding;
friend class ActionQueue;
friend class ActionNode;
public:
Action() { Product = 0, Time = 0,Seller="unknown",custmer="unknown",E_bidding=0; }
Action(int Product, int Time,string Seller,string Custmer,double E_bidding)
{ Product=product, Time = time,Seller=seller,Custmer=custmer,E-binding=ebinding; }
void setProduct(int product) { Product=product; }
int getProduct() { return Product; }
void setTime (int time){ Time=time;}
int getTime () { return Time; }
void setSeller (string seller){ Seller = seller; }
string getSeller () { return Seller; }
void setCustomer (string custmor) { Customer = custmor;}
string getCustomer () { return Customer; }
void setE_bidding (double ebidding) { E_bidding = ebidding; }
double getE_bidding () { return E_bidding; }
void printActionDetails()
{
cout<<"Auction Details: "<<"\n"<<getE_bidding()<<"\n"<<getCustomer()<<"\n"<<getProduct()
<<"\n"<<getSeller()<<"\n"<<getTime()<<endl;
}
};
class ActionNode
{
public:
ActionNode Data;
ActionPosition Data;
ActionNode* next;
ActionNode()
{
Data.Product = 0, Data.Time = 0,Data.Seller="unknown",Data.Customer="unknown",Data.E_bidding=0 ;
}
ActionNode(int product, int time,string seller,string customer,double ebidding)
{
Data.Product = product, Data.Time = time,Data.Seller=seller,Data.Customer=customer,Data.E_bidding=ebidding;
}
};
class ActionQueue
{
ActionQueue newnode;
ActionNode* rear, * front;
int counter;
public:
ActionQueue() { rear = front = NULL; counter = 0; }
~ActionQueue() { Action Actiondata; while (!isempty()) dequeue(Actiondata); }
bool isempty() { if (counter == 0) return true; else return false; }
void enqueue(Action ActionData) {
stockNode* newnode = new stockNode; //error
newnode->Data = ActionData;
if (isempty())
{
rear = newnode;
front = newnode;
}
else {
rear->next = newnode;
rear = newnode;
}
counter++;
}
bool dequeue(Action& data)
{
if (isempty()) { cout << "Error:the queue is empty\n"; return false; }
else {
ActionNode* nextnode;
nextnode = front->next;
data = front->Data;
delete front;
front = nextnode;
counter--;
return true;
}
}
int find(int Product)
{
ActionNode* currNode = front;
int position = 1;
while (currNode->Data.Product != Product)
{
if (currNode != NULL)
currNode = currNode->next;
position++;
}
if (currNode) return position;
return -1;
}
void display()
{
cout << endl;
cout << "Front-->";
ActionNode* currNode = front;
for (int i = 0; i < counter; i++)
{
if (i == 0) cout << "\t";
else cout << "\t\t";
cout << " Product : " << currNode->Data.Product << "\t" <<
"Time :" << currNode->Data.Time<<"\t"<<
"Seller:"<< currNode->Data.Seller<<"\t"<<
"Customer :" << currNode->Data.Custmoer<<"\t"<<
"E_bidding :" << currNode->Data.E_bidding<<"\t";
if (i != counter - 1) cout << endl;
else cout << "\t<-- Rear" << endl;
currNode = currNode->next;
}
}
bool modify()
{
if (isempty())
{
cout << "Error ,the queue is empty \n"; return false;
}
else
{
int product1,Time1;
string Seller1, Customer1;
double E_bidding1;
cout << "\nEnter Product : "; cin>>product1;
cout<< "\nEnter Time :" ;cin>>Time1;
cout<< "\nEnter Seller:";cin>>Seller1;
cout<< "\nEnter Customer :" ;cin>>Customer1;
cout<< "\nEnter E_bidding :" ;cin>>E_bidding1;
rear->Data.product = product1;
rear->Data.Time = Time1;
rear->Data.Seller = Seller1;
rear->Data.Customer = Customer1;
rear->Data.E_bidding = E_bidding1;
return true;
}
}
};
int main()
{
Seller sellerObject, valseller;
SellerQueue SellerQueue1;
Product productObject ,valPruduct;
ProductQueue productQueue1;
Customer customerObject, valCostumer;
customerQueue customerQueue1;
Action ActionObject, Action,valAction;
ActionQueue Actionqueue1;
string string1, string2, string3;
int int1, int2, int3,index, intChoice, customerloop, customerTotal;
double double1,double2;
char charChoice;
bool bool1;
float float1,float2,float3;
for (int i = 0;; i++)
{
cout << "Main menu:\n";
cout << "1.Product\n";
cout << "2.Seller\n";
cout << "3.Customer\n";
cout << "4.ACtion\n";
cin >> intChoice;
switch (intChoice)
{
case 1:
cout << "a.Display\n";
cout << "b.Insert\n";
cout << "c.Delete\n";
cout << "d.Modify\n";
cout << "e.Find\n";
cin >> charChoice;
switch (charChoice)
{
case'a':
ProductQueue.display();
break;
case 'b':
cout << "Enter product BarCode: "; cin >> int1;
cout << "Enter Quantity : "; cin >> int1;
cout << "Enter product price : "; cin >> double1;
productObject.setBarCode(int1);
productObject.setQuantity(int1);
productObject.setPrice(double1);
ProductQueue.enqueue(ProductObject);
break;
case'c':
cout << ProductQueue.dequeue(valPruduct) << endl;
valPruduct.printProductDetails();
break;
case 'd':
cout << "modify rear element : ";
ProductQueue.modify();
break;
case'e':
cout << "Enter Product BarCode to find it "; cin >> int1;
cout << "\nthe element index : "<<ProductQueue.find(int1) << endl;
break;
case'f':
break;
}
break;
case 2:
cout << "a.Display\n";
cout << "b.Insert\n";
cout << "c.Delete\n";
cout << "d.Modify\n";
cout << "e.Find\n";
cin >> charChoice;
switch (charChoice)
{
case'a':
SellerQueue1.display();
break;
case 'b':
cout << "Enter Seller name : "; cin >> string1;
cout << "Enter Seller ID : "; cin >> int2;
cout << "Enter contact : "; cin >> int1;
cout << "Enter Reating : "; cin >> float1;
sellerObject.setName(string1);
sellerObject.setID(string2); //error
sellerObject.setcontact(int1);
sellerObject.setReating(float1);
SellerQueue.enqueue(sellerObject);
break;
case'c':
SellerQueue.dequeue(valseller);
valseller.printSellerInfo();
break;
case 'd' :
cout << "modify rear element : ";
SellerQueue.modify();
break;
case'e':
cout << "Enter Seller ID to find him : "; cin >> int1;
cout << "\nthe element index : " << SellerQueue.find(int1)<<endl;
break;
case'f':
break;
}
break;
case 3:
cout << "a.Display\n";
cout << "b.Insert\n";
cout << "c.Delete\n";
cout << "d.Modify\n";
cout << "e.Find\n";
cin >> charChoice;
switch (charChoice)
{
case'a':
customerQueue1.display();
break;
case 'b':
// Customer = 0;
cout << "Enter customer Name : "; cin >> string3;
cout << "Enter customer id : "; cin >> int1;
cout << "Enter customer point : "; cin >> float2;
cout << "Enter customer number : "; cin >> int2;
cout << "Enter BarCode : "; cin >> int2;
cout << "Enter Quantity : "; cin >> double1;
cout << "\tprice : " ;cin >>double2 ;
customerObject.setID(int1);
customerObject.setName(string3);
customerObject.setPoint(flaot3);//??error
customerObject.setProductforCustomer(int1, int2, double1);
customerQueue1.enqueue(customerObject);
for (int j = 1;; i++)
{
cout << "Do you want add a new Prodect to this customer ? \n 1 ""YES"" \n 2 ""NO"" ";
cin >> customerloop;
if (customerloop == 1)
{
cout << "Enter Product BarCode : "; cin >> int1;
cout << "Enter Product Quantity : "; cin >> int2;
cout << "Enter Product price : "; cin >> double1;
// customerObject.setBarCode();
customerObject.setProductforCustomer(int1, int2, double1);
customerQueue1.enqueue(customerObject);
}
else break;
}
break;
case'c':
cout << customerQueue1.dequeue(valCostumer);
valCostumer.printCustomerInfo();
break;
case 'd':
cout << "modify rear element : ";
customerQueue1.modify();
break;
case'e':
cout << "Enter customer id to find him : "; cin >> int1;
cout << "\nthe element index : " << customerQueue1.find(int1)<<endl;
break;
case'f':
break;
}
break;
case 4:
cout << "a.Display\n";
cout << "b.Insert\n";
cout << "c.Delete\n";
cout << "d.Modify\n";
cout << "e.Find\n";
cout << "f.Exit\n";
cin >> charChoice;
switch (charChoice)
{
case'a':
ActionQueue.display();
break;
case 'b':
cout << "\nEnter Product : "; cin>>int1;
cout<< "\nEnter Time :" ;cin>>int2;
cout<< "\nEnter Seller:";cin>>string1;
cout<< "\nEnter Customer :" ;cin>>string2;
cout<< "\nEnter E_bidding :" ;cin>>double1;
ActionObject.setProduct(int1);
ActionObject.setTime(int2);
ActionObject.setSeller(string1);
ActionObject.setCustomer(string2);
ActionObject.setE_bidding(double1);
ActionQueue.enqueue(ActionObject);
break;
case'c':
cout << ActionQueue.dequeue(valAction);
valAction.printActionDetails();
break;
case 'd':
cout << "modify rear element : ";
ActionQueue.modify();
break;
case'e':
cout << "Enter the Prodect to find it :"; cin >> int1;
cout << "\nthe element index : " << ActionQueue.find(int1)<<endl;
break;
case'f':
break;
}
break;
}
}
}
we study a small part about queue so we don't have full knowledge about it. we want to know why in call error, the class customer and class Action have most of the problem also the call in the int main .
most error like this [Error] expected unqualified-id before '.' token.
the error in name or wasn't declared in the scope it's ok we can fix it
pleas help
Related
I have implemented an integer type Queue using an array in C++ as:
This is not a circular queue so we don't have to bother for the empty space after filling it once and then deleting some values.
class IntQueue
{
private:
int *queueArray;
int queueSize;
int rear, front;
public:
IntQueue(int); // Constructor
~IntQueue(void);
void Enqueue(int);
int Dequeue(void);
bool isFull(void);
bool isEmpty(void);
void Display(void);
};
// Constructor
IntQueue::IntQueue(int size)
{
queueArray = new int[size];
queueSize = size;
rear = -1;
front = -1;
}
// Destructor
IntQueue::~IntQueue(void)
{
delete [] queueArray;
}
// Enqueue function
void IntQueue::Enqueue(int num)
{
if (isFull())
{
cout << "The Queue is full.\n";
}
else
{
rear++;
queueArray[rear] = num;
}
}
// Dequeue function
int IntQueue::Dequeue()
{
int num;
if (isEmpty())
{
cout << "The Queue is empty.\n";
}
else
{
front++;
num = queueArray[front];
}
return num;
}
//isFull function
bool IntQueue::isFull(void)
{
bool status;
if (rear == queueSize - 1)
status = true;
else
status = false;
return status;
}
//isEmpty function
bool IntQueue::isEmpty(void)
{
bool status;
if (front == rear)
status = true;
else
status = false;
return status;
}
// Display function
void IntQueue::Display()
{
if(isEmpty())
{
cout << "The Queue is empty.\n";
}
for(int i = front++; i <= rear; i++)
{
cout << "queueArray[" << i << "] = " << queueArray[i] << endl;
}
}
// Main function
int main()
{
int option, queueCapacity, value;
cout << endl << "Enter size of queue: ";
cin >> queueCapacity;
IntQueue *queue = new IntQueue(queueCapacity);
Menu:
cout << endl << "Queue implementation using Array" << endl;
cout << "--------------------------------" << endl;
cout << "1. Enqueue" << endl;
cout << "2. Dequeue" << endl;
cout << "3. Display Queue" << endl;
cout << "4. Display Menu" << endl;
cout << "5. Exit" << endl;
cout << "--------------------------------" << endl;
YourOption:
cout << endl << "Your option: ";
cin >> option;
switch(option)
{
case 1:
// Enqueue
cout << "Enter value to enqueue: ";
cin >> value;
queue->Enqueue(value);
goto YourOption;
case 2:
// Dequeue
int data;
data = queue->Dequeue();
cout << data << " is dequeued!";
goto YourOption;
case 3:
// Display
queue->Display();
goto YourOption;
case 4:
goto Menu;
case 5:
exit(0);
default:
cout << "Invalid option!" << endl;
break;
}
delete queue;
return 0;
}
The variable rear is initially -1. I have checked isFull() function as if rear is equal to the size of Queue, then the queue is full, not otherwise. However, to check queue emptiness, I compared if rear == front, then empty, not otherwise. But after executing it, by opting 2 from the menu, it displays some random value sometimes and the message i.e., "The Queue is empty".
What is the problem in this example?
void enqueue(int x)
{
//cout << "Enter the DAta " << endl;
//cin >> x;
if (front==(rear+1)%size)
{
cout << "Queue Is overflow::" << endl;
return;
}
else if (rear==-1&&front==-1)
{
//cout << "enter the To EnQueue :" << endl;
front = rear = 0;
queue[rear] = x;
}
else if (rear==0 && front==0)
{
rear = rear + 1 % size;
queue[rear] = x;
}
else
{
rear++;
queue[rear] = x;
}
}
Your queue is working properly but you have need to check some variable values like in the Enqueue(int num) function you have forgot to update the variable front=0
void IntQueue::Enqueue(int num)
{
if (isFull())
{
cout << "The Queue is full.\n";
}
else
{
rear++;
queueArray[rear] = num;
}
}
because at the initial time when you display the values front=-1.
So, add the front=0 in the enqueue function like this,
void IntQueue::Enqueue(int num)
{
if (isFull())
{
cout << "The Queue is full.\n";
}
else
{
front=0;
rear++;
queueArray[rear] = num;
}
}
Hope you got it. if you have any confusion comment it.
For my project I need to make a hash table the has stock information in it.I think I have most of what I need to do working, but I have an issue filling the hash table with information form a text file. When the file is empty my program starts up and displays the menu correctly, but when I put information into the text file it freezes forever until Putty kills the program. Also, when I try to add stocks it doesn't seem to take the information correctly, which may be the cause of it taking forever to read in from the file. I've tried messing around with a couple of things in the file but nothing has worked for me.
Edit:
after adding some cout statements I've found that in the loop "while(!in.eof())"
is infinite and never reaches the end of the file and I'm not sure why.
hashTable.cpp:
#include "hashtable.h"
#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
void hashTable::initializeTable()
{
table = new node*[capacity];
int i;
for(i=0; i<capacity; i++)
table[i] = NULL;
}
hashTable::hashTable() : capacity(DEFAULT_CAPACITY), size(0)
{
initializeTable();
}
hashTable::hashTable(char * fileName) : capacity(DEFAULT_CAPACITY), size(0)
{
ifstream in;
data currData;
char tickerSymbol[100];
char name[100];
float netVal;
char date[100];
float yToD;
initializeTable();
in.open(fileName);
if(!in)
{
cerr << "fail to open " << fileName << " for input!" << endl;
return;
}
in.get(tickerSymbol, 100, ';');
while(!in.eof())
{
in.ignore(100, ';');
in.get(name, 100, ';');
in.ignore(100, ';');
in.ignore(100, ';');
in >> netVal;
in.ignore(100, ';');
in.get(date, 100, ';');
in.ignore(100, ';');
in >> yToD;
in.ignore(100, '\n');
currData.setTickerSymbol (tickerSymbol);
currData.setName (name);
currData.setNetValue(netVal);
currData.setDate(date);
currData.setYToD(yToD);
insert(currData);
in.get(tickerSymbol, 10, ';');
}
in.close ();
}
hashTable::hashTable(const hashTable& aTable):capacity(aTable.capacity), size(aTable.size)
{
table = new node*[capacity];
int i;
for(i=0; i<capacity; i++)
{
if (aTable.table[i] == NULL)
table[i] = NULL;
else
{
table[i] = new node(aTable.table[i]->item);
node * srcNode = aTable.table[i]->next;
node * destNode = table[i];
while(srcNode)
{
destNode->next = new node(srcNode->item);
destNode = destNode->next;
srcNode = srcNode->next;
}
destNode->next = NULL;
}
}
}
const hashTable& hashTable::operator= (const hashTable& aTable)
{
if(this == &aTable)
return *this;
else
{
destroyTable();
table = new node*[capacity];
capacity = aTable.capacity;
size = aTable.size;
int i;
for(i=0; i<capacity; i++)
{
if (aTable.table[i] == NULL)
table[i] = NULL;
else
{
table[i] = new node(aTable.table[i]->item);
node * srcNode = aTable.table[i]->next;
node * destNode = table[i];
while(srcNode)
{
destNode->next = new node(srcNode->item);
destNode = destNode->next;
srcNode = srcNode->next;
}
destNode->next = NULL;
}
}
return *this;
}
}
void hashTable::destroyTable ()
{
int i;
for(i=0; i<capacity; i++)
{
node * head = table[i];
node * curr;
while(head)
{
curr = head->next;
head->next = NULL;
delete head;
head = curr;
}
}
delete [] table;
}
hashTable::~hashTable()
{
destroyTable();
}
void hashTable::insert (const data& aData)
{
char key[100];
aData.getTickerSymbol(key);
int index = calculateIndex(key);
node * newNode = new node(aData);
newNode->next = table[index];
table[index] = newNode;
size++;
}
bool hashTable::remove (char * key)
{
int index = calculateIndex(key);
node * curr = table[index];
node * prev = NULL;
char id[100];
while (curr)
{
curr->item.getTickerSymbol (id);
if(strcmp(key, id) == 0)
{
if(!prev)
table[index] = curr->next;
else
prev->next = curr->next;
curr->next = NULL;
delete curr;
size--;
return true;
}
else
{
prev = curr;
curr = curr->next;
}
}
return false;
}
bool hashTable::retrieve (char * key, data & aData)const
{
int index = calculateIndex(key);
node * curr = table[index];
char id[100];
while (curr)
{
curr->item.getTickerSymbol (id);
if(strcmp(key, id) == 0)
{
aData = curr->item;
return true;
}
else
curr = curr->next;
}
return false;
}
void hashTable::display (void)const
{
int i;
node * curr;
cout << "Data in the table: " << endl << endl;
for(i=0; i<capacity; i++)
{
for(curr = table[i]; curr; curr = curr->next)
cout << '\t' << curr->item << endl;
}
}
int hashTable::getSize (void) const
{
return size;
}
void hashTable::writeOut(char * fileName)
{
ofstream out;
out.open(fileName);
if(!out)
{
cerr << "fail to open " << fileName << " for output!" << endl;
return;
}
int i;
char tickerSymbol[100];
char name[100];
node * curr;
for(i=0; i<capacity; i++)
{
for(curr = table[i]; curr; curr = curr->next)
{
curr->item.getTickerSymbol (tickerSymbol);
curr->item.getName (name);
out << tickerSymbol << ';' << name << ';' << curr->item.getNetValue () << '\n';
}
}
out.close ();
}
int hashTable::calculateIndex (char * key)const
{
char * c = key;
int total = 0;
while(*c)
{
total += *c;
c++;
}
return total%capacity;
}
main.cpp
#include <stdlib.h>
//#include <crtdbg.h>
#include "hashtable.h"
#include <iostream>
using namespace std;
void displayMenu();
char getCommand();
void executeCmd(char command, hashTable& aTable);
void getStock(data & stock);
int getInt(char * prompt);
float getFloat(char * prompt);
void getString(char * prompt, char * input);
void display(const hashTable & aTable);
const int MAX_LEN = 100;
int main()
{
char command = 'a';
char fileName[] = "data.dat";
hashTable stocks(fileName);
displayMenu();
command = getCommand();
while(command != 'q')
{
executeCmd(command, stocks);
displayMenu();
command = getCommand();
}
stocks.writeOut (fileName);
cout << "\nThank you for using CWMS!" << endl << endl;
return 0;
}
void displayMenu()
{
cout << "\nWelcome to CS Stock Management System! "<< endl;
cout << "\ta> add a stock" << endl
<< "\tr> remove a stock" << endl
<< "\ts> search for a stock" << endl
<< "\tl> list all the stocks" << endl
<< "\tq> quit the application" << endl << endl;
}
char getCommand()
{
char cmd;
cout << "Please enter your choice (a, r, s, l or q):";
cin >> cmd;
cin.ignore(100, '\n');
return tolower(cmd);
}
void executeCmd(char command, hashTable& aTable)
{
data stock;
char key[MAX_LEN];
switch(command)
{
case 'a': getStock(stock);
aTable.insert (stock);
cout << endl << "the stock has been saved in the database. " << endl;
break;
case 'r': getString("\nPlease enter the ticker symbol of the stock you want to remove: ", key);
aTable.remove(key);
cout << endl << key << " has been removed from the database. " << endl;
break;
case 's': getString("\nPlease enter the ticker symbol of the stock you want to search: ", key);
aTable.retrieve (key, stock);
cout << endl << "Information about " << key << ": " << endl << '\t' << stock << endl;
break;
case 'l': display(aTable);
break;
default: cout << "illegal command!" << endl;
break;
}
}
void display(const hashTable & aTable)
{
aTable.display();
}
void getStock(data & stock)
{
char tickerSymbol[MAX_LEN];
char name[MAX_LEN];
float netVal;
char date[MAX_LEN];
float yToD;
cout << "\nPlease enter information about the stock: " << endl;
getString("\tticker symbol: ", tickerSymbol);
getString("\tname: ", name);
netVal = getFloat("\tnet asset value: ");
getString("\tdate of that value: ", date);
yToD = getFloat("\tyear to date return: ");
stock.setTickerSymbol (tickerSymbol);
stock.setName (name);
stock.setNetValue (netVal);
stock.setDate (date);
stock.setYToD (yToD);
}
int getInt(char * prompt)
{
int temp;
cout << prompt;
cin >> temp;
while(!cin)
{
cin.clear ();
cin.ignore(100, '\n');
cout << "Illegal input -- try again: ";
cin >> temp;
}
cin.ignore(100, '\n');
return temp;
}
float getFloat(char * prompt)
{
float temp;
cout << prompt;
cin >> temp;
while(!cin)
{
cin.clear ();
cin.ignore(100, '\n');
cout << "Illegal input -- try again: ";
cin >> temp;
}
cin.ignore(100, '\n');
return temp;
}
void getString(char * prompt, char * input)
{
cout << prompt;
cin.get(input, MAX_LEN, '\n');
cin.ignore (100, '\n');
}
Nevermind, I just didn't have semicolons at the end of the lines in my data.dat file so it was never reaching the end.
I am doing a data structure project and it is important to write my own template linked list class implementation ,it is required that:
Each visa account can do a transaction using the visa card and the transaction is recorded in his account with date and amount of money due.
My steps :
make a list of accounts in the system.
each account has it's list of cards, as it is required issuing another visa card with different number but to the same account.
make for each visa a list of transactions.
My problem:
that the transactions made by the card not saved in the list of transactions that is defined in the card class.. you can check the function settrans to see how I implemented it . how can I fix that ?
2.The balance "The sum of all transactions" is not updated, which I need it later to let the user pay.
NOTE : The main is not completed and there is another data I need to do another functions not completed yet so no problem if you found excess paramters.
and I didn't put pre or post conditions yet.
the header file with all functions and classes :
#include <iostream>
#include <string>
using namespace std;
template<class T> class list;
class account;
class card;
class transaction;
//Node class
template<class T> class node
{
public:
node() : data(0), next(NULL){}
T getdata() { return data; }
node * getnext(){ return next; }
void setnext(node * n) { next = n; }
node(T v) : data(v), next(NULL) {}
friend list < T >;
private:
T data;
node * next;
};
template<class T> class list
{
node<T> * head;
public:
list() : head(NULL){}
void add(T data)
{
node <T> *temp = new node<T>(data);
temp->next = head;
head = temp;
}
void printaccounts();
void printcards();
void printtransactions();
bool checkaccount(string n, string p);
account getaccount(string n, string p);
bool checkcard(int i, string p);
card getcard(int i, string p);
};
//Transaction Class
class transaction
{
public:
void pushtrans(int ch, int a, int cat, int m, int d, string co);
void newtrans();
int getcharge() { return charge; }
int getage(){ return age; }
string getcompany(){ return company; }
int getcategory(){ return category; }
private:
int charge;
string company;
int month;
int day;
int category;
int age;
};
void transaction::pushtrans(int ch, int a, int cat, int m, int d, string co)
{
charge = ch;
age = a;
category = cat;
month = m;
day = d;
company = co;
}
//Card Class
class card
{
public:
card();
void pushcard(string p, int m, int d, int x);
int getid(){ return id; }
int getm(){ return month; }
int getd(){ return day; }
int getb(){ return balance; }
void settrans();
string getpassword(){ return password;}
transaction gettransobj(){ return t; }
list<transaction> getlist(){ return tl; }
private:
int id =0;
string password;
int balance =0;
int month;
int day;
list<transaction> tl;
transaction t;
};
card::card()
{
password = "";
balance = 0;
month = 0;
day = 0;
}
void card::pushcard(string p, int m, int d, int x)
{
password = p;
month = m;
day = d;
id = x;
}
//Account Class
class account
{
public:
void pushaccount(string n, string p);
string getname(){ return name; }
string getaccpassword() { return passwrod; }
card getcard(){ return c; }
list<card> getclist() { return cl; }
void setcard();
private:
string name;
string passwrod;
card c;
list<card> cl;
};
void account::pushaccount(string n, string p)
{
name = n;
passwrod = p;
}
void account::setcard()
{
string p; int m, d,x;
cout << "\n _Please enter your Password: ";
cin >> p;
cout << "\n _Please enter the Month: ";
cin >> m;
cout << "\n _Please enter your Date: ";
cin >> d;
x = c.getid() + 1;
cout << "Your ID is : " << x;
c.pushcard(p, m, d, x);
cl.add(c);
}
template<class T>
void list<T>:: printaccounts()
{
cout << "The Accounts: \n";
node <T> *temp = head;
while (temp != nullptr)
{
cout << temp->data.getname() << endl;
temp = temp->next;
}
}
template<class T>
bool list<T>::checkaccount(string n, string p)
{
bool c = false;
node <T> * temp = head;
while (temp != nullptr)
{
if (temp->data.getname() == n && temp->data.getaccpassword() == p)
{
c = true;
return c;
}
temp = temp->next;
}
return c;
}
template<class T>
account list<T>::getaccount(string n, string p)
{
node <T> * temp = head;
account a;
while (temp != nullptr)
{
if (temp->data.getname() == n && temp->data.getaccpassword() == p)
{
a = temp->getdata();
return a;
}
temp = temp->next;
}
return a;
}
template<class T>
void list<T>::printcards()
{
cout << "\nThe Cards: \n";
node <T> *temp = head;
while (temp != nullptr)
{
cout << temp->data.getid() << endl;
temp = temp->next;
}
}
template<class T>
bool list<T>::checkcard(int i, string p)
{
bool c = false;
node <T> * temp = head;
while (temp != nullptr)
{
if (temp->data.getid() == i && temp->data.getpassword() == p)
{
c = true;
return c;
}
temp = temp->next;
}
return c;
}
template<class T>
card list<T>::getcard(int i, string p)
{
node <T> * temp = head;
card c;
while (temp != nullptr)
{
if (temp->data.getid() == i && temp->data.getpassword() == p)
{
c = temp->getdata();
return c;
}
temp = temp->next;
}
return c;
}
void card::settrans()
{
string s; int m, d,a,c,p;
cout << "\n _Please enter charge: ";
cin >> p;
cout << "\n _Please enter the Month: ";
cin >> m;
cout << "\n _Please enter your Date: ";
cin >> d;
cout << "\n _Choose the Category: \n";
cout << "|--------------|" << endl;
cout << "| 1.Food |" << endl;
cout << "| 2.Clothes |" << endl;
cout << "| 3.Medicine |" << endl;
cout << "|--------------|" << endl;
cin >> c;
cout << "\n _Please enter the Company/Shop: ";
cin >> s;
cout << "\n _Please enter your age: ";
cin >> a;
balance += p;
cout << "Balance = " << balance;
t.pushtrans(p, a, c, m, d, s);
tl.add(t);
}
template<class T>
void list<T>::printtransactions()
{
int i = 1;
cout << "\nThe Transactions: \n";
node <T> *temp = head;
while (temp != nullptr)
{
cout << i << "." << temp->data.getcompany() << "\tCHARGE: " << temp->data.getcharge() << endl;
temp = temp->next;
i++;
}
}
The main :
#include <iostream>
#include <string>
#include "Header1.h"
using namespace std;
void main()
{
list<account> A;
account acc;
//int x;
while (true)
{
int choice, choice2, i , m, d;
string n, p;
cout << "*** Welcome to ASU Bank ***" << endl;
cout << "|-------------------------|" << endl;
cout << "| 1. Get a New Account |" << endl;
cout << "| 2. Open My Account |" << endl;
cout << "| 3. Statistics |" << endl;
cout << "|-------------------------|" << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Please enter your Name: ";
cin >> n;
cout << "\n Please enter your Password: ";
cin >> p;
acc.pushaccount(n, p);
A.add(acc);
A.printaccounts();
break;
case 2:
cout << "-Please enter your Name: ";
cin >> n;
cout << "\n -Please enter your Password: ";
cin >> p;
if (A.checkaccount(n, p))
{
acc = A.getaccount(n, p);
list<card> C;
list<transaction> T;
card c;
transaction t;
while (true)
{
cout << "\n|-------------------------|" << endl;
cout << "| 1. Get a New Card |" << endl;
cout << "| 2. Make Transaction |" << endl;
cout << "| 3. Print Transactions |" << endl;
cout << "| 4. Pay |" << endl;
cout << "| 5. Companies Record |" << endl;
cout << "| 6. Get Balance |" << endl;
cout << "| 7. Main Menu |" << endl;
cout << "|-------------------------|" << endl;
cin >> choice2;
switch (choice2)
{
case 1:
//ba2a ye3ml cards with different ids and push them in the list YEAY :D
acc.setcard();
C = acc.getclist();
C.printcards();
break;
case 2:
cout << "-Please enter your card ID: ";
cin >> i;
cout << "\n -Please enter your card Password: ";
cin >> p;
if (C.checkcard(i, p))
{
//bey3ml add fy list gedida w mesh bey7seb balance..same error
c = C.getcard(i, p);
c.settrans();
c.getlist().printtransactions();
}
else cout << "Invalid Entery !\n";
break;
case 3:
cout << "-Please enter your card ID: ";
cin >> i;
cout << "\n -Please enter your card Password: ";
cin >> p;
if (acc.getclist().checkcard(i, p))
{
c = acc.getclist().getcard(i, p);
c.getlist().printtransactions();
}
else cout << "Invalid Entery !\n";
break;
case 4:
default:
break;
}
}
}
else
cout << "The Account doesn't exist please check your info.\n";
break;
default:
break;
}
}
}
Edited part:
1. changed all the data in node class to pointer to data
2.
card * list<T>::getcard(int i, string p)
{
node <T> * temp = head;
card* c;
while (temp != nullptr)
{
if (temp->data.getid() == i && temp->data.getpassword() == p)
{
c = temp;
return &c;
}
temp = temp->next;
}
return &c;
}
solved part is that there is a transaction list with different transactions saved in it but the account list and card list have the problem:
if I add john to the accounts and then joe
it will have two accounts with the name joe.
and same problem with cards list
So I've basically have most of the programming almost complete. I wanted to add a menu that displays an output. For example, a list of records is created. After it is all entered, I would like for it to display only the patients that smoke or have high blood pressure or high fat diet when selecting a number from the menu. Now I am stuck trying to figure that out but can't seem to wrap my head around it. Any suggestions of how I can get it work? Right now it is only set to display all of the records at once.
//Program Description: An interface program that displays patients records.
#include <iostream>
#include <string>
using namespace std;
struct Node
{
char name[20];
int age;
string smoker;
string hbp;
string hfd;
int points;
Node *ptr;
};
Node *startPtr = NULL;
void getInfo()
{
Node *p, *p2;
p = new Node;
int agePoints;
int smkPoints;
int hbpPoints;
int hfdPoints;
cout << " Please enter the name of the patient : ";
cin >> p->name;
cout << " Please enter the age of the patient : ";
cin >> p->age;
cout << " Is he/she a smoker (y/n) : ";
cin >> p->smoker;
cout << " Does he/she have high blood pressure? (y/n) : ";
cin >> p->hbp;
cout << " Does he/she have a high fat diet? (y/n) : ";
cin >> p->hfd;
cout << endl;
p->ptr = NULL;
// Age point system
if (p-> age > 30) {
agePoints = 3;
}
else if (p->age > 20)
{
agePoints = 2;
}
else
{
agePoints = 1;
}
// Habits Points System
if (p->smoker == "Y" || p->smoker == "y")
{
p->smoker = "Yes";
smkPoints = 4;
}
else
{
p->smoker = "non smoker";
smkPoints = 0;
}
if (p->hbp == "Y" || p->hbp == "y")
{
p->hbp = "High blood pressure";
hbpPoints = 2;
}
else
{
p->hbp = "Normal blood pressure";
hbpPoints = 0;
}
if (p->hfd == "Y" || p->hfd == "y")
{
p->hfd = "High fat diet";
hfdPoints = 1;
}
else
{
p->hfd = "Low fat diet";
hfdPoints = 0;
}
p->points = agePoints + smkPoints + hbpPoints + hfdPoints;
// Set up link to this node
if (startPtr == NULL) {
startPtr = p;
}
else
{
p2 = startPtr;
while (p2->ptr != NULL)
p2 = p2->ptr;
p2->ptr = p;
}
}
void delete_start_node()
{
Node *p;
p = startPtr;
startPtr = startPtr->ptr;
delete p;
}
void delete_end_node()
{
Node *p1, *p2;
if (startPtr == NULL)
cout << "The List is empty!\n";
else
{
p1 = startPtr;
if (p1->ptr == NULL)
{
delete p1;
startPtr = NULL;
}
else
{
while (p1->ptr != NULL)
{
p2 = p1;
p1 = p1->ptr;
}
delete p1;
p1->ptr = NULL;
}
}
}
void disp()
{
Node *p;
p = startPtr;
if (p == NULL)
cout << "Empty List!\n";
while (p != NULL)
{
if (p == NULL)
cout << "Empty List!\n";
cout << " Name : " << p->name << endl;
cout << " Age : " << p->age << endl;
cout << " Smoker : " << p->smoker << endl;
cout << " Blood Pressure : " << p->hbp << endl;
cout << " Fat Diet : " << p->hfd << endl;
cout << " Points : " << p->points << endl;
cout << endl;
p = p->ptr;
}
}
Node* removeptr(Node* prev)
{
if (prev)
{
if (prev->ptr)
{
Node* p = prev->ptr;
prev->ptr = p->ptr;
return p;
}
}
else if (startPtr)
{
Node* p = startPtr;
startPtr = startPtr->ptr;
return p;
}
return NULL;
}
// sort by age in ascending order
void sortAge()
{
Node* startPtr2 = NULL;
while (startPtr)
{
Node* prev = NULL;
Node* curr = startPtr;
Node* prevMax = NULL;
int max = startPtr->age;
while (curr)
{
if (curr->age > max)
{
max = curr->age;
prevMax = prev;
}
prev = curr;
curr = curr->ptr;
}
// Node with the highest age found pass throug the list.
Node* xferNode = removeptr(prevMax);
if (xferNode)
{
xferNode->ptr = startPtr2;
startPtr2 = xferNode;
}
}
startPtr = startPtr2;
}
int main()
{
Node *p;
p = startPtr;
char selection;
do
{
cout << " Patient Menu\n";
cout << " =============================================\n";
cout << " 1. Insert a new record\n";
cout << " 2. List smoker patients\n"; // smoker patient
cout << " 3. List HBP patients\n"; // high blood pressure patient
cout << " 4. List HFD patients\n"; // high fat diet patient
cout << " 5. Delete a patient record by given name\n";
cout << " 6. Exit the program\n";
cout << " =============================================\n";
cout << " Enter your selection: ";
cin >> selection;
cout << endl;
switch (selection)
{
case '1':
getInfo();
break;
case '2':
disp();
break;
case '3':
break;
case '4':
break;
case '5':
break;
case '6':
cout << " Goodbye!\n";
return 0;
break;
default:
break;
}
}while (selection != 6);
/*
disp();
cout << "________________________________________________\n";
sortAge();
disp();*/
system("pause");
return 0;
}
Node *smokers, *hbp, *hfd = NULL;
You could keep a separate linked list for each type - smoker, hbp, hfd and change
void disp()
// to
void disp(Node* linkedList)
and print list given to it
case '2':
disp(smokers);
break;
case '3':
disp(hbp);
break;
case '4':
disp(hfd);
break;
btw, smells like a homework :)
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)?