Hash table reading in from file - c++

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.

Related

problem with the Queue and int main program in c++?

#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

Reading data from file into queue in c++

I am having trouble figuring out how to get my input data into my queue... I am so close to getting this to work right.
I know I am just confused about how things are working. I have used example code and my instructions to come up with a working program that appears to be working correctly (other than not actually putting my input file data into the queue). I bypassed the function I was trying to make for this. In addition to this, I was trying to write a function to remove an employee from the queue (which I think does work), but I am not sure I was able to get it right...
I have not taken a programming class for over 10 years and really would love to get any help in understanding what I am doing and getting that darn data into the queue.
Below is my main driver file. I will provide my header file code if needed. Thanks in advance for any help you can provide on this.
//Program Assignment #3
//Creates Queue as a Linked Structure
#include<iostream>
#include<string>
#include<fstream>
#include"Employee.h"
#include"LinkedQ.h"
using namespace std;
struct Node
{
LinkedQ nodeQ;
Employee EmpNumber;
Employee LastName;
Employee FirstName;
Employee ServiceYears;
};
void loadFile(LinkedQ &);
void addEmp(LinkedQ &);
void delEmp(LinkedQ &);
int main()
{
LinkedQ empList;
int choice;
int numIn, yearsIn;
string LastName;
string FirstName;
LinkedQ empIn;
ifstream input;
input.open("Employee.txt");
while (input)
{
input >> numIn >> LastName >> FirstName >> yearsIn;
if (input)
{
cout << "this is where we load data from the file into the queue\n";
system("pause");
//empIn.Enqueue(numIn, LastName, FirstName, yearsIn);
//empList.addEmp(empIn);
}
}
input.close();
do
{
//display menu
system("cls");
cout << "\t\tMenu: \n"
<< "\t1. Add Employee\n"
<< "\t2. Remove Employee\n"
<< "\t3. Count of Employees\n"
<< "\t4. Quit\n\n";
cout << "Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
addEmp(empList); // call to function to add an employee to the queue
break;
case 2:
delEmp(empList); // call to fucntion to remove an employee from the queue
break;
case 3:
cout << endl << "Count of Employees: "
<< empList.GetLength() << endl; // See how many employees are in the queue
system("pause");
break;
case 4:
cout << "End of Program"; // End Program
break;
default:
cout << "Not a valid choice!" << endl;
cout << "Choose Again."; // Handling incorrect inputs
system("pause");
break;
}
} while (choice != 4); // If choice is not 4, continue running program
return 0;
}
//***********************************
//Loads the file (having trouble figuring out how to implement this part)
//***********************************
void loadFile(Employee &empList)
{
int numIn, yearsIn;
string LastName;
string FirstName;
LinkedQ empIn;
ifstream input;
input.open("Employee.txt");
while (input)
{
input >> numIn >> LastName >> FirstName >> yearsIn;
if (input)
{
cout << "this is where we load data from the file into the queue";
//empIn.setFields(numIn, LastName, FirstName, yearsIn);
//empList.addEmp(empIn);
}
}
input.close();
}
//***************************************
//add an employee
//***************************************
void addEmp(LinkedQ &empList)
{
Employee newEmp;
newEmp.user();
empList.Enqueue(newEmp);
}
//****************************************
//remove a employee
//****************************************
void delEmp(LinkedQ &empList)
{
Employee EmpToRemove;
int empNum;
// bool successful;
cout << "Please enter EMPLOYEE NUMBER of employee to remove:";
cin >> empNum;
EmpToRemove.setEmpNumber(empNum);
empList.Dequeue(EmpToRemove);
//successful = empList.Dequeue(EmpToRemove);
//if (successful == true)
//{
cout << "Removed" << endl << endl;
system("pause");
//}
//else
//{
// cout << "Emp Not found" << endl << endl;
//}
}
Here is the LinkedQ implementation file:
//LinkedQ class
#include "LinkedQ.h"
#include <cstddef>
#include <new>
struct NodeType
{
Employee info;
NodeType* next;
};
LinkedQ::LinkedQ(void)
{
newNode = nullptr;
front = NULL;
rear = NULL;
length = 0;
}
void LinkedQ::MakeEmpty()
{
NodeType* tempPtr;
while (front != NULL)
{
tempPtr = front;
front = front->next;
delete tempPtr;
}
rear = NULL;
}
LinkedQ::~LinkedQ(void)
{
MakeEmpty();
}
bool LinkedQ::IsFull() const
{
NodeType* location;
try
{
location = new NodeType;
delete location;
return false;
}
catch (std::bad_alloc exception)
{
return true;
}
}
bool LinkedQ::IsEmpty() const
{
return (front == NULL);
}
void LinkedQ::Enqueue(Employee newItem)
{
if (IsFull())
cout << "Queue is Full";
// throw FullQueue();
else
{
NodeType* newNode;
newNode = new NodeType;
newNode->info = newItem;
newNode->next = NULL;
if (rear == NULL)
{
front = newNode;
}
else
{
rear->next = newNode;
}
rear = newNode;
length++;
}
}
void LinkedQ::Dequeue(Employee& item)
{
if (IsEmpty())
{
//throw EmptyQueue();
cout << "Queue is empty";
}
else
{
NodeType* tempPtr;
tempPtr = front;
item = front->info;
front = front->next;
if (front == NULL)
{
rear = NULL;
}
delete tempPtr;
length--;
}
}
int LinkedQ::GetLength() const
{
return length;
}
And here is the Employee implementation file:
//employee Class
#include"Employee.h"
//Constructor
Employee::Employee()
{
EmpNum = 0;
}
//setters
void Employee::setEmpNumber(int eNum)
{
EmpNum = eNum;
}
void Employee::setEmpName(string LName)
{
LastName = LName;
}
void Employee::setEmpFirstName(string FName)
{
FirstName = FName;
}
void Employee::setYearsService(int years)
{
YearsService = years;
}
void Employee::setFields(int num, string LN, string FN, int years)
{
EmpNum = num;
LastName = LN;
FirstName = FN;
YearsService = years;
}
void Employee::user()
{
string inputString;
int intNumber;
cout << "Employee Number ";
cin >> intNumber;
while (intNumber <= 0)
{
cout << "Employee Number ";
cin >> intNumber;
}
EmpNum = intNumber;
cout << "Last Name: ";
cin >> inputString;
LastName = inputString;
cout << "First Name: ";
cin >> inputString;
FirstName = inputString;
cout << "Years of Service: ";
cin >> intNumber;
while (intNumber < 0)
{
cout << "Years of Service ";
cin >> intNumber;
}
cout << endl;
YearsService = intNumber;
}
//getters
const int Employee::getEmpNumber()
{
return EmpNum;
}
const string Employee::getLastName()
{
return LastName;
}
const string Employee::getFirstName()
{
return FirstName;
}
const int Employee::getYearsService()
{
return YearsService;
}
//overloads
bool Employee::operator == (const Employee &right)
{
bool status;
if ( EmpNum == right.EmpNum)
status = true;
else
status = false;
return status;
}
bool Employee::operator != (const Employee &right)
{
bool status;
if (EmpNum != right.EmpNum)
status = true;
else
status = false;
return status;
}
I think the parameter of loadFile should be of type LinkedQ, which, if I understand it correctly, is the queue class/struct, and the empIn variable should be of type Employee.
Edit:
The method you call on the empList object should be Enqueue, instead of addEmp.

How to create a doubly linked list of integers in ascending sorted order?

I'm having hard time to finish the code to get the following steps:
how to read in a file of positive integers (>0)?
how to create a doubly linked list of integers in ascending sorted order?
how to write a method to print the entire list in ascending or descending order (input parameter ā€˜Aā€™ or ā€˜Dā€™ tells direction to print)?
how notify the user with a message if the number to add is already in the list or if the number is not in the list if they to delete a number not in the list.
There's no error when i run the program, just trying to solve the 4 steps above.
Here's what I have done so far
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct node
{
int number;
node *next;
};
bool isEmpty(node *head);
char menu();
void insertAsFirstElement(node *&head, node *&last, int number);
void inser(node*&head, node*&last, int number);
void remove(node *&head, node *&last);
void showlist(node *current);
int numIntElement(ifstream&x);
int main() {
string filename;
cout << " Please enter the name of the file = ";
cin >> filename;
ifstream myfile;
myfile.open(filename);
if (!myfile.is_open()) {
cout << endl << " failed to open file, check that it exists and you have access \n" << "\n" << endl;
}
else if (myfile.is_open())
{
ifstream x;
numIntElement(x);
cout << " File exists \n";
////
node * head = NULL;
node *last = NULL;
char choice;
int number;
do {
choice = menu();
switch (choice)
{
case '1':
cout << " Please enter number : ";
cin >> number;
inser(head, last, number);
break;
case '2':
remove(head, last);
case '3':
showlist(head);
break;
default:
break;
}
} while (choice != '4');
{
}
}
system("pause");
return 0;
}
int numIntElement(ifstream&x) {
int n = 0;
int m;
ifstream myfile("file.txt");
int countsingfie = 0;
while (!myfile.eof())
{
myfile >> n;
countsingfie += n;
if (countsingfie == 0) {
cout << "Error : file exist but no data " << endl;
}
cout << "total number " << countsingfie << "\n" << endl;
return countsingfie;
}
}
bool isEmpty(node *head) {
if (head == NULL) {
return true;
}
else
{
return false;
}
}
char menu() {
char choice;
cout << " Main Menu \n";
cout << " 1 . Add a number \n";
cout << " 2 . Delete a number from the list \n";
cout << " 3 . Show the list \n";
cout << " 4. Exit \n";
cin >> choice;
return choice;
}
void insertAsFirstElement(node *&head, node *&last, int number) {
node *temp = new node;
temp->number = number;
temp->next = NULL;
head = temp;
last = temp;
}
void inser(node*&head, node*&last, int number) {
if (isEmpty(head)>0){
insertAsFirstElement(head, last, number);
}
else if (isEmpty(head) < 0)
{
cout << " Please enter a number above 0 " << endl;
}
else
{
node *temp = new node;
temp->number = number;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void remove(node *&head, node *&last) {
if (isEmpty(head)) {
cout << " Sorry, The list is already empty \n";
}
else if (head == last)
{
delete head;
head = NULL;
last = NULL;
}
else
{
node *temp = head;
head = head->next;
delete temp;
}
}
void showlist(node *current) {
if (isEmpty(current)) {
cout << " The list is empty \n";
}
else
{
cout << " The list contains: \n ";
while (current != NULL)
{
cout << current->number << endl;
current = current->next;
}
}
}

How to delete a node from linked list in cpp from the memory permanantly,

Here is my code i have written. Whats wrong in it. Every time i delete nodes from starting to end its going fine but when deleting randomly its breaking the program.
I have to delete the nodes from the heap/memory permanently not just breaking the links between them.
#include <iostream>
using namespace std;
class Node
{
private:
int data;
Node *next;
public:
Node(){}
Node(int d)
{
data = d;
next = NULL;
}
void SetNext(Node *nextNode)
{
next = nextNode;
}
int Data()
{
return data;
}
Node* Next()
{
return next;
}
};
class List
{
Node *head;
public:
List() { head = NULL; };
void Insert(int d)
{
int value;
value = d;
Node* n1 = new Node(value);
n1->SetNext(NULL);
Node *temp = head;
if(temp != NULL)
{
while(temp->Next() != NULL)
{
temp = temp->Next();
}
temp->SetNext(n1);
}
else
head = n1;
};
void Delete()
{
int value;
cout<<"enter a value to Delete"<<endl;
cin>>value;
Node* temp;
temp = head;
Node *prev;
if(temp == NULL)
{
cout<<"List is empty, deletion is not possible"<<endl;
}
else
{
if(temp->Next() == NULL)
{
if(temp->Data() == value)
{
delete temp;
head = NULL;
}
else
{
cout<<"Entered Data value is not available in the List"<<endl;
}
}
else if((temp->Data() == value))
{
head = temp->Next();
delete temp;
}
else
{
while(temp->Next() != NULL)
{
prev = temp;
temp = temp->Next();
if((temp->Data() == value) && (temp->Next() != NULL))
{
prev->SetNext(temp->Next());
delete temp;
}
else if(temp->Data() == value && temp->Next() == NULL)
{
prev->SetNext(NULL);
delete temp;
}
}
}
}
};
void Print()
{
Node *temp = head;
if ( temp == NULL )
{
cout << "EMPTY" << endl;
return;
}
if ( temp->Next() == NULL )
{
cout << temp->Data();
cout << " --> ";
cout << "NULL" << endl;
}
else
{
do
{
cout << temp->Data();
cout << " --> ";
temp = temp->Next();
}
while ( temp != NULL );
cout << "NULL" << endl;
}
};
void isEmpty()
{
if(head == NULL)
cout<<"List is Empty"<<endl;
else
cout<<"List is not Empty"<<endl;
};
};
int main()
{
List l1;
char ch;
do
{
cout<<"\n Linked List "<<endl;
cout<<"I. Insert \t D. Delete"<<endl;
cout<<"P. Print \t E. isEmpty \t X.EXIT"<<endl;
cout<<"Enter Your Choice :"<<endl;
cin>>ch;
if((ch>=97)&&(ch<=122))
{
ch=ch-32;
}
switch(ch)
{
case 'I': int value;
cout<<"\n***** Inserting *****"<<endl;
cout<<"enter a value to insert"<<endl;
cin>>value;
l1.Insert(value);
break;
case 'D': cout<<"\n***** Delete *****"<<endl;
l1.Print();
cout<<"\nDelete any value from the above listed"<<endl;
l1.Delete();
system("pause");
break;
case 'P': cout<<"\n***** Print *****"<<endl;
l1.Print();
system("pause");
break;
case 'E': cout<<"\n***** isEmpty *****"<<endl;
l1.isEmpty();
system("pause");
break;
case 'X': exit(1);
break;
default: cout<<"\n Invalid Choice"<<endl;
}
system("cls");
}
while(1);
system("pause");
return 0;
}
Your Delete() function is overly complicated. It can be greatly simplified. For that matter, most of your List code can be simplified. Try something more like this instead:
#include <iostream>
using namespace std;
class Node
{
private:
int data;
Node *next;
public:
Node(int d = 0) : data(d), next(NULL) {}
void SetNext(Node *nextNode)
{
next = nextNode;
}
int Data() const
{
return data;
}
Node* Next() const
{
return next;
}
};
class List
{
private:
Node *head;
Node *tail;
public:
List() : head(NULL), tail(NULL) {}
~List() { Clear(); }
void Clear()
{
Node *temp = head;
Node *next;
head = tail = NULL;
while ( temp != NULL )
{
next = temp->Next();
delete temp;
temp = next;
}
}
void Insert(int d)
{
Node* n1 = new Node(d);
if ( head == NULL )
head = n1;
if ( tail != NULL )
tail->SetNext(n1);
tail = n1;
}
bool Delete(int value)
{
Node* temp = head;
Node *prev = NULL;
while ( temp != NULL )
{
Node* next = temp->Next();
if ( temp->Data() == value )
{
if( prev != NULL )
prev->SetNext(next);
if( head == temp )
head = next;
if( tail == temp )
tail = prev;
delete temp;
return true;
}
prev = temp;
temp = next;
}
return false;
}
void Print() const
{
Node *temp = head;
if ( temp == NULL )
{
cout << "EMPTY" << endl;
}
else
{
do
{
cout << temp->Data() << " --> ";
temp = temp->Next();
}
while ( temp != NULL );
cout << " NULL" << endl;
}
}
bool isEmpty() const
{
return (head == NULL);
}
};
int main()
{
List l1;
char ch;
do
{
cout << "\n Linked List " < <endl;
cout << "I. Insert \t D. Delete \t C. Clear" << endl;
cout << "P. Print \t E. isEmpty \t X. EXIT" << endl;
cout << "Enter Your Choice :" << endl;
cin >> ch;
if ( (ch >= 'a') && (ch <= 'z') )
{
ch -= 32;
}
switch (ch)
{
case 'I':
{
int value;
cout << "\n***** Inserting *****" << endl;
cout << "enter a number to insert" << endl;
if ( cin >> value )
l1.Insert(value);
else
{
cout << "\nYou did not enter a valid number" << endl;
system("pause");
}
break;
}
case 'D':
{
cout << "\n***** Delete *****" << endl;
if ( l1.isEmpty() )
{
cout << "List is empty, deletion is not possible" << endl;
break;
}
l1.Print();
cout << "\nDelete any number from the above list" << endl;
int value;
cout << "enter a number to delete" << endl;
if ( cin >> value )
{
if ( l1.Delete(value) )
cout << "Entered number has been deleted from the List" << endl;
else
cout << "Entered number is not available in the List" << endl;
}
else
cout << "\nYou did not enter a valid number" << endl;
system("pause");
break;
}
case 'C':
{
cout << "\n***** Clear *****" << endl;
l1.Clear();
cout << "List is now empty" << endl;
system("pause");
break;
}
case 'P':
{
cout << "\n***** Print *****" << endl;
l1.Print();
system("pause");
break;
}
case 'E':
{
cout << "\n***** isEmpty *****" << endl;
if ( l1.isEmpty() )
cout << "List is Empty" << endl;
else
cout << "List is not Empty" << endl;
system("pause");
break;
}
case 'X':
exit(1);
break;
default:
cout << "\n Invalid Choice" << endl;
system("pause");
break;
}
system("cls");
}
while (1);
system("pause");
return 0;
}
With that said, you really should be using the std::list class instead, or even the std::forward_list class in C++11 and later. Let the STL manage the nodes for you, eg:
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class List
{
private:
list<int> l;
public:
void Clear()
{
l.clear();
}
void Insert(int d)
{
l.push_back(d);
}
bool Delete(int value)
{
list<int>::iterator iter = find(l.begin(), l.end(), value);
if( iter != l.end() )
{
l.erase(iter);
return true;
}
return false;
}
void Print() const
{
if ( l.empty() )
{
cout << "EMPTY" << endl;
}
else
{
list<int>::iterator iter = l.begin();
do
{
cout << *iter << " --> ";
}
while ( ++iter != l.end() );
cout << " NULL" << endl;
}
}
bool isEmpty() const
{
return l.empty();
}
};

Output Is very slightly off in ordered traversal of Binary search tree

#ifndef MOVIETREE_H_INCLUDED
#define MOVIETREE_H_INCLUDED
#include <iostream>
#include <cstdlib>
#include <vector>
#include <math.h>
using namespace std;
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
int ranking;
string title;
int year;
int quantity;
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
bool isEmpty() const { return root==NULL; }
void insert(int ranking, string title, int year, int quantity);
void remove(string title);
void inorder(tree_node* p);
double orderrating(string title);
void print_inorder();
void search(string d);
void rent(string l);
// void split(const string& s, char c,vector<string>& v);
};
double BinarySearchTree::orderrating(string title)
{
// string letters[52]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","o","p","q","r","s","t","u","v","w","x","y","z"};
char letters[54]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z',':','a','b','c','d','e','f','g','h','i','j',
'k','l','m','o','p','q','r','s','t','u','v','w','x','y','z',' '};
double rating = 0;
for(int i = 0; i<title.length();i++)
{
for(int j = 0;j<52;j++)
{
if(letters[j]==title.at(i))
{
rating = rating+pow(10,-i)*((j)%26);
}
}
}
//cout<<rating<<endl;
return rating;
}
void split(const string& s, char c, vector<string>& v)
{
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length()));
}
}
void BinarySearchTree::insert(int ranking, string title, int year, int quantity)
{
tree_node* t = new tree_node;
tree_node* parent;
t->quantity = quantity;
t->ranking = ranking;
t->title = title;
t->year = year;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if(isEmpty()) root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while(curr)
{
parent = curr;
if(orderrating(t->title) > orderrating(curr->title)) curr = curr->right;
else curr = curr->left;
}
if(orderrating(t->title) <= orderrating(parent->title))
parent->left = t;
else
parent->right = t;
}
}
void BinarySearchTree::search(string l)
{
//Locate the element
bool found = false;
double d = orderrating(l);
if(isEmpty())
{
cout<<" This Tree is empty! "<<endl;
return;
}
tree_node* curr;
tree_node* parent;
curr = root;
while(curr != NULL)
{
if(curr->title == l)
{
found = true;
cout << "Movie Info:" << endl;
cout << "===========" << endl;
cout << "Ranking:" <<curr->ranking<<endl;
cout << "Title:"<<curr->title<<endl;
cout << "Year:" <<curr->year<<endl;
cout << "Quantity:"<<curr->quantity<<endl;
break;
}
else
{
parent = curr;
if(d>orderrating(curr->title)) curr = curr->right;
else curr = curr->left;
}
}
if(!found)
{
cout<<" Movie not found."<<endl;
return;
}
}
void BinarySearchTree::rent(string l)
{
//Locate the element
bool found = false;
double d = orderrating(l);
if(isEmpty())
{
cout<<"This Tree is empty!"<<endl;
return;
}
tree_node* curr;
tree_node* parent;
curr = root;
while(curr != NULL)
{
if(curr->title == l)
{
found = true;
if(curr->quantity!=0)
{curr->quantity = curr->quantity-1;
cout << "Movie has been rented." << endl;
cout << "Movie Info:" << endl;
cout << "===========" << endl;
cout << "Ranking:" <<curr->ranking<<endl;
cout << "Title:" <<curr->title<<endl;
cout << "Year:" <<curr->year<<endl;
cout << "Quantity:" << curr->quantity<<endl;
}
else{//If movie is in stock
cout << "Movie out of stock." << endl;
}
break;
}
else
{
parent = curr;
if(d>orderrating(curr->title)) curr = curr->right;
else curr = curr->left;
}
}
if(!found)
{
cout<<"Movie not found."<<endl;
return;
}
}
void BinarySearchTree::print_inorder()
{
inorder(root);
}
int counter =0;
void BinarySearchTree::inorder(tree_node* p)
{
if(p != NULL)
{
if(p->left) inorder(p->left);
cout<<"Movie: "<<p->title<<endl;
//cout<<" "<<p->quantity<<endl;//cout<<counter<<endl;
if(p->right) inorder(p->right);
}
else return;
}
#endif // MOVIETREE_H_INCLUDED
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <stdlib.h>
#include "MovieTree.h"
using namespace std;
struct MovieInfo{
int ranking;
string title;
int year;
int quantity;
};
int main(int argc, char * argv[])
{
//creates struct to store movie info
MovieInfo MovieInfo1[51];
int counter1 = 0;
std::string word1;
//"Assignment5Movies.txt"
ifstream myfile1("Assignment5Movies.txt");
if (myfile1.is_open())
{
std::string line;
while ( getline (myfile1,line) )
{
//need delimeter for file.
vector<string> v;
string s = line;
split(s, ',', v);
for (unsigned int i = 0; i < v.size(); ++i)
//add individual atributes to moviearray
{//cout<<v[i]<<endl;
if(i%4==1){MovieInfo1[counter1].title = v[i];}
if(i%4==2){ int value =atoi(v[i].c_str()); MovieInfo1[counter1].year = value;}
if(i%4==3){ int value =atoi(v[i].c_str()); MovieInfo1[counter1].quantity = value;}
if(i%4==0){ int value =atoi(v[i].c_str()); MovieInfo1[counter1].ranking = value;}
}//cout<<counter1<<endl;
counter1++;
}
myfile1.close();
}
// construct Binary tree
BinarySearchTree b;
for(int i = 0; i<counter1;i++)
{
b.insert(MovieInfo1[i].ranking,MovieInfo1[i].title,MovieInfo1[i].year, MovieInfo1[i].quantity);
}
int option;
//do while loop for user interface
do{
cout << "======Main Menu=====" << endl;
cout << "1. Find a movie" << endl;
cout << "2. Rent a movie" << endl;
cout << "3. Print the inventory" << endl;
cout << "4. Quit" << endl;
cin>>option;
cin.ignore(10000,'\n');
if (option==1)//find movie
{
cout << "Enter title:" << endl;
string temp;
cin >> ws;
getline(cin, temp);
b.search(temp);
}
if (option==2)//rent movie
{
cout << "Enter title:" << endl;
string temp;
cin >> ws;
getline(cin, temp);
b.rent(temp);
}
if (option==3)//print inventory
{
b.print_inorder();
}
}while(option!=4);
cout << "Goodbye!" << endl;
}
here is my main file and my header, basically my output is off for like two movies and I don't know why. any input would be appreciated. and yes I should have used a string.compare(string) also when given a txt file it prints
12 Angry Men
Back to the Future
Casablanaca
... the rest are in order except
Lord of the Rings: the two towers
Lord of the Rings: the fellowship of the ring
Lord of the Rings: the return of the king
are in the right place, but ordered incorrectly.
The value of orderrating() for these three movies is identical. Therefore, they will be printed in the opposite order that you insert them into the tree.
Lord of the Rings: the two towers
Lord of the Rings: the fellowship of the ring
Lord of the Rings: the return of the king
There's only so much precision in a double.