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.
Related
#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
UPDATED....New issue with addstudent function.
I made some changes based on feedback. I also made an update to the addstudent()function based on the assignment requirements and I am running into a strange issue.
The requirements for the addstudent function are that the parameters be a string id, string name, and string major. I added a line that allocates a new student node in this function, but it seems that only the ID is being kept. When I print the student information, the ID shows up, but the name and major are both blank. Where am I going wrong?
#include <iostream>
#include <string.h>
using namespace std;
class Student
{
public:
string ID;
string name;
string major;
public:
Student *next;
Student()
{
ID = "0";
name = "0";
major = "0";
next = NULL;
}
Student(string id, string name, string major)
{
ID = id;
name = name;
major = major;
next = NULL;
}
};
class Classroom
{
public:
Student* head;
Classroom()
{
head = NULL;
}
Classroom(Student* n)
{
head = n;
}
void addStudent(string id, string name, string major)
{
Student *n=new Student(id, name, major);
Student* current;
if (head == NULL)
{
n->next = head;
head = n;
}
else if(head->name > n->name)
{
n->next = head;
head = n;
}
else
{
current = head;
while (current->next!=NULL &&
current->next->name < n->name)
{
current = current->next;
}
n->next = current->next;
current->next = n;
}
}
void removeStudent(string id)
{
if (!head)
{
cout << "No students exist in this list.\n";
return;
}
Student **precurrent = &head,
*current = head;
while (current)
{
if (current->ID == id)
{
*precurrent = current->next;
cout<< "Student removed from list.\n";
return;
}
precurrent = ¤t->next;
current = current->next;
}
cout << "No student exists with this ID.\n";
}
void print()
{
if (!head) {
cout << "No students in list.\n";
return;
}
for (Student *temp = head; temp; temp = temp->next)
cout <<"\nStudent Information:\n Student ID: " << temp->ID
<< "\n Student Name: " << temp->name
<< "\n Student Major: " << temp->major << '\n';
}
void print(string id)
{
if (!head)
{
cout << "No students in list.\n";
return;
}
for (Student *temp = head; temp; temp = temp->next)
{
if (temp->ID == id)
{
cout <<"Student Information: \n"<< "Student ID: " << temp->ID <<'\n' << "Student Name: " << temp->name <<'\n' << "Student Major: " << temp->major << '\n';
return;
}
if(temp==NULL)
{
cout<<"Student ID does not exist.\n";
return;
}
}
}
bool isEmpty()
{
if (head == NULL)
return true;
else;
return false;
}
int getSize()
{
int count = 0;
if(head==NULL)
{
return count;
}
Student* temp = head;
while (temp != NULL)
{
temp = temp->next;
count++;
}
return count;
}
Student *at(int index)
{
Student *temp = head;
for (int i=1; i < index && temp; i++, temp = temp->next) {}
if (!temp)
cout << "Index not found.\n";
return temp;
}
};
int main()
{
Classroom cs;
int choice;
do
{
cout <<"\nPlease select an option below: (Enter 0 to exit)\n"
<< "1. Add student.\n"
<< "2. Remove student.\n"
<< "3. Print all student.\n"
<< "4. Print specific student.\n"
<< "5. Print student at index.\n"
<< "6. Print number of students.\n"
<< "7. Check if student list is empty.\n\n";
cin >> choice;
Student* s1 = new Student();
switch (choice)
{
case 0:
break;
case 1:
{
string id, name, major;
cout << "Enter Student ID:";
cin.ignore();
getline(cin, id);
cout << "Enter Student Name:";
getline(cin, name);
cout << "Enter Student Major:";
getline(cin, major);
cs.addStudent(id, name, major);
break;
}
case 2:
{
string id;
cout << "Enter Student ID of the Student to be removed: ";
cin >> id;
cs.removeStudent(id);
break;
}
case 3:
cs.print();
break;
case 4:
{
string id;
cout << "Enter ID of student to print: ";
cin >> id;
cs.print(id);
break;
}
case 5:
{
int index;
if(cs.isEmpty())
{
cout<< "No Students Exists.\n";
break;
}
cout << "Enter index to print: ";
cin >> index;
Student *s=cs.at(index);
if(s)
cs.print(s->ID);
break;
}
case 6:
cout << "There are "<< cs.getSize() << " students.\n";
break;
case 7:
if(cs.isEmpty())
cout<< "No Students Exists.\n";
else
cout << "The list is not empty.\n";
break;
default:
cout << "Enter valid option (0-7)\n";
}
} while (choice != 0);
return 0;
}
You have a large number of small errors that result in trouble throughout your code. With at() you are simply making it much harder than it needs to be. When you think about your at() function, there are simply two-conditions which must be true as you iterate over your list:
Your iteration counter must be less than the index, e.g. i < index (in C/C++ indexes are zero based on everything -- keep your code consistent) and
When you advance your list pointer, temp = temp->next, temp must not be NULL (or just temp for short).
You can put those together as:
Student *at(int index)
{
Student *temp = head;
int i = 0; /* C/C++ use zero based indexes */
for (; i < index && temp; i++, temp = temp->next) {}
if (!temp)
std::cerr << "error: index not found.\n";
return temp;
}
(where you have 2 loop-variables, temp and i and you use the comma operator to increment both in the for loop)
Similarly, you make your void removeStudent(std::string id) function much more complicated than it needs to be. When working with a list, you never keep track of a previous pointer, instead you use a pointer-to-pointer to hold the address of the current node (say Student **ppcurrent;) and you use a temporary pointer to point to the current node (say Student *pcurrent;).
When pcurrent->ID == id to remove, you simply set the pointer at the current address (as held by ppcurrent) to the next pointer in the list overwriting the Student to be removed with the ->next in the list. The beauty of this method is there are no special cases for head or any other node in the list, you simply replace the node at the current address with the next, e.g.
void removeStudent(std::string id)
{
if (!head) {
std::cout << "No students exist in this list.\n";
return;
}
Student **ppcurrent = &head,
*pcurrent = head;
while (pcurrent)
{
if (pcurrent->ID == id) {
*ppcurrent = pcurrent->next;
return;
}
ppcurrent = &pcurrent->next;
pcurrent = pcurrent->next;
}
std::cout << "No student exists with this ID.\n";
}
(See Linus on Understanding Pointers and see Why is “using namespace std;” considered bad practice?)
Your handling of std::cin and your use of std::cin.ignore() will miss cases where extraneous characters exist in stdin. You need to VALIDATE every use of std::cin to check for a stream error and then std::cin.clear() any stream error caused by a type mismatch or otherwise before you can use .ignore() and then you must empty all characters from stdin, not just one. Putting that together, you have a few issues to correct in main(), e.g.
do
{
std::cout <<"\nPlease select an option below: (Enter 0 to exit)\n"
" 1. Add student.\n"
" 2. Remove student.\n"
" 3. Print all student.\n"
" 4. Print specific student.\n"
" 5. Print student at index.\n"
" 6. Print number of students.\n"
" 7. Check if student list is empty.\n\n"
"choice: ";
if (!(std::cin >> choice)) {
std::cerr << "\nerror: invalid integer.\n";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
and then similarly with case: 5 of your switch() statement:
std::cout << "\nEnter index to print (zero based): ";
if (!(std::cin >> index)) {
std::cerr << "\nerror: invalid integer.\n";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
There were probably a lot more than needed correcting, but the bulk of the remaining problems were just awkwardness in the way things were coded (which is to be expected given that you are just learning C++, so nothing against the way to approached it -- that is normal and to be expected). For example, above, you only need one std::cout to output your entire menu, and you don't add a std::endl; after outputting a string-literal, just include the '\n' at the end of the literal, example:
std::cout << "hello world\n";
instead of
std::cout << "hello world" << std::endl;
It's not that the use of std::endl; is wrong, it's simply that it is not needed. The same applies to your nesting of if { } else { } within your various functions where you can simply return if you if condition is met making the else superfluous and leading to unnecessary levels of code indention. For example print() can simply be:
void print()
{
if (!head) {
std::cout << "No students in list.\n";
return;
}
for (Student *temp = head; temp; temp = temp->next)
std::cout <<"\nStudent Information:\n Student ID: " << temp->ID
<< "\n Student Name: " << temp->name
<< "\n Student Major: " << temp->major << '\n';
}
We will leave it to you to make the remaining comparisons of the changes to your code. The only other note is try and limit your variables to the scope they are needed. You only allocate a new Student if the user selects add from the menu. Otherwise you are just needlessly allocating for all other menu choices. While you may have done this to avoid the error if you tried to declare and allocate within your case 1: statement, you simply need to enclose the entire case in a block, e.g. { .... } and you are free to declare anything you need within that code block, e.g.
case 1: {
std::string id {}, name {}, major {};
std::cout << "\nEnter Student ID: ";
getline (std::cin, id);
std::cout << "Enter Student Name: ";
getline (std::cin, name);
std::cout << "Enter Student Major: ";
getline(std::cin, major);
Student *s1 = new Student(id, name, major);
cs.addStudent(s1);
break;
}
or
case 5: {
int index;
if (cs.isEmpty()) {
std::cout << "\nlist is empty.\n";
break;
}
std::cout << "\nEnter index to print (zero based): ";
if (!(std::cin >> index)) {
std::cerr << "\nerror: invalid integer.\n";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
Student *s = cs.at(index);
if (s)
cs.print (s->ID);
break;
}
(note: from my comment below your question, this is where you must validate the return from at() before calling print())
If you put all the pieces together, you would have:
#include <iostream>
#include <string>
#include <limits>
class Student
{
public:
std::string ID {}, name {}, major {};
Student *next;
Student()
{
ID = "0";
name = "0";
major = "0";
next = NULL;
}
Student(std::string ids, std::string names, std::string majors)
{
ID = ids;
name = names;
major = majors;
next = NULL;
}
};
class Classroom
{
public:
Student* head;
Classroom() { head = NULL; }
Classroom(Student* n) { head = n; }
void addStudent(Student *n)
{
Student* current;
if (head == NULL || head->name >= n->name) {
n->next = head;
head = n;
return;
}
current = head;
while (current->next && current->next->name < n->name)
current = current->next;
n->next = current->next;
current->next = n;
}
void removeStudent(std::string id)
{
if (!head) {
std::cout << "No students exist in this list.\n";
return;
}
Student **ppcurrent = &head,
*pcurrent = head;
while (pcurrent)
{
if (pcurrent->ID == id) {
*ppcurrent = pcurrent->next;
return;
}
ppcurrent = &pcurrent->next;
pcurrent = pcurrent->next;
}
std::cout << "No student exists with this ID.\n";
}
void print()
{
if (!head) {
std::cout << "No students in list.\n";
return;
}
for (Student *temp = head; temp; temp = temp->next)
std::cout <<"\nStudent Information:\n Student ID: " << temp->ID
<< "\n Student Name: " << temp->name
<< "\n Student Major: " << temp->major << '\n';
}
void print(std::string id)
{
if (!head) {
std::cout << "No students in list.\n";
return;
}
for (Student *temp = head; temp; temp = temp->next) {
if (temp->ID == id) {
std::cout <<"\nStudent Information:\n Student ID: " << temp->ID
<< "\n Student Name: " << temp->name
<< "\n Student Major: " << temp->major << '\n';
return;
}
}
std::cerr << "error: ID '" << id << "' not found.\n";
}
bool isEmpty()
{
if (head)
return false;
return true;
}
int getSize()
{
int count = 0;
Student* temp = head;
while (temp) {
temp = temp->next;
count++;
}
return count;
}
Student *at(int index)
{
Student *temp = head;
int i = 0; /* C/C++ use zero based indexes */
for (; i < index && temp; i++, temp = temp->next) {}
if (!temp)
std::cerr << "error: index not found.\n";
return temp;
}
};
int main()
{
Classroom cs;
int choice;
do
{
std::cout <<"\nPlease select an option below: (Enter 0 to exit)\n"
" 1. Add student.\n"
" 2. Remove student.\n"
" 3. Print all student.\n"
" 4. Print specific student.\n"
" 5. Print student at index.\n"
" 6. Print number of students.\n"
" 7. Check if student list is empty.\n\n"
"choice: ";
if (!(std::cin >> choice)) {
std::cerr << "\nerror: invalid integer.\n";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
switch (choice)
{
case 0:
break;
case 1: {
std::string id {}, name {}, major {};
std::cout << "\nEnter Student ID: ";
getline (std::cin, id);
std::cout << "Enter Student Name: ";
getline (std::cin, name);
std::cout << "Enter Student Major: ";
getline(std::cin, major);
Student *s1 = new Student(id, name, major);
cs.addStudent(s1);
break;
}
case 2: {
std::string id {};
std::cout << "\nEnter Student ID of the Student to be removed: ";
getline (std::cin, id);
cs.removeStudent(id);
break;
}
case 3:
cs.print();
break;
case 4: {
std::string id;
std::cout << "\nEnter ID of student to print: ";
getline (std::cin, id);
cs.print(id);
break;
}
case 5: {
int index;
if (cs.isEmpty()) {
std::cout << "\nlist is empty.\n";
break;
}
std::cout << "\nEnter index to print (zero based): ";
if (!(std::cin >> index)) {
std::cerr << "\nerror: invalid integer.\n";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
Student *s = cs.at(index);
if (s)
cs.print (s->ID);
break;
}
case 6:
std::cout << "\nThere are "<< cs.getSize() << " students.\n";
break;
case 7:
if (cs.isEmpty())
std::cout<< "\nNo Students Exists.\n";
else
std::cout << "\nThe list is not empty.\n";
break;
default:
std::cout << "\nEnter valid option (0-7)\n";
}
} while (choice);
return 0;
}
Take time to understand the changes made and if you have further questions, just drop a comment below.
After going through your code, there are some flaws which need to be addressed.
void addStudent(Student *n)
{
Student* current;
if (head == NULL || head->name >= n->name)
{
n->next = head;
head = n;
}
else
{
current = head;
while (current->next!=NULL &&
current->next->name < n->name)
{
current = current->next;
}
n->next = current->next;
current->next = n;
}
In the above code,
Condition of string comparison need to be corrected. Using >= may not yield always the desired result as per alphabetical order is concerned. Reason being that it compares length or first element both. Instead "compare" function of string can be used.
The condition "if(head == NULL || head->name..." will jump into a situation of operating on a null pointer. So, use nested if statement instead of clubbing both condition under single if.
Coming to "at()" function:
Student* at(int index)
{
Student* temp = head;
int count=1;
if(head==NULL)
{
cout << "No students exist." << endl;
}
else
{
while(temp!=NULL)
{
if(count==index)
{
return(temp);
break;
}
else
{
count++;
temp = temp->next;
}
}
while(temp==NULL)
{
cout << "Index not found."<< endl;
break;
}
}
You need to de-reference the pointer in order to get the value (under switch condition, case 5) as you are returning a pointer.
Your function is not returning a value in all condition. You must finally return a pointer under each condition.
Also, instead of "while(temp == NULL)", you need to use "if(temp == NULL)"
Lastly use "nullptr" instead of "NULL" if you are working on C++11 or above version and use inbuilt containers like std::list if possible.
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;
}
}
}
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.
For a school programming assignment I built an application that stores a list of objects in a sequential list object. The sequential list class has a method to insert a new object into the list, it checks first to see if the list already has the maximum number of entries allowed and if it does returns an error. For some reason I'm unable to insert a new object into the list (I keep getting the "Max list size exceeded" error) even though there aren't any entries in it to start.
I ran it with a breakpoint to see if the size data member was increasing somehow but that doesn't seem to be the case here.
Please ignore the poor code quality, still just learning... Feel free to make any recommendations :)
Here's the main program:
#include<iostream>
#include<string>
#include "aseqlist.h"
using namespace std;
void PrintByGender (const SeqList& L, char gender)
{
int size = L.ListSize();
int count = 0;
while (count < size)
{
if (gender == L.GetData(count).getGender())
{
L.GetData(count).PrintEmployee();
}
count++;
}
}
int InList (const SeqList& L, char *lname, Employee& Emp)
{
int found = 0;
Emp.setLast(lname);
if (L.Find(Emp) == 1)
{
found = 1;
Emp.PrintEmployee();
}
return found;
}
int main()
{
SeqList obj1;
bool close = false;
string choice = "";
do
{
cout << "Please choose what you would like to do: " << "\n";
cout << "N = New record, D = Delete record, P = Print by gender, S = Search and E = Exit" << "\n";
cin >> choice;
cin.ignore();
if (choice == "n" || choice == "N")
{
string first, last;
int age;
char gen;
double empNum;
cout << "First name: ";
cin >> first;
cout << "Last name: ";
cin >> last;
cout << "Age: ";
cin >> age;
cout << "Gender ('M' Or 'F'): ";
cin >> gen;
cout << "Employee Number: ";
cin >> empNum;
Employee newEmp;
newEmp.ReadEmployee(first, last, age, gen, empNum);
obj1.Insert(newEmp);
}
if (choice == "e" || choice == "E")
{
close = true;
}
if (choice == "p" || choice == "P")
{
char genderSearch;
cout << "Male = M, Female = F";
cin >> genderSearch;
cin.ignore();
PrintByGender(obj1, genderSearch);
}
if (choice == "d" || choice == "D")
{
string last;
cout << "Which employee? (Enter Last Name): ";
cin >> last;
cin.ignore();
Employee emp;
emp.setLast(last);
obj1.Delete(emp);
cout << "Deleted";
}
if (choice == "s" || choice == "S")
{
char lnameSearch;
cout << "Last Name?: ";
cin >> lnameSearch;
cin.ignore();
Employee emp;
char *ptrSearch;
ptrSearch = &lnameSearch;
InList(obj1, ptrSearch, emp);
if (emp.getFirst() != "")
{
emp.PrintEmployee();
}
}
}
while (close != true);
};
And here's the header file for the class declarations:
#include <iostream>
using namespace std;
const int MaxListSize = 6;
// You will need to change the typedef in the following line
// from the data type int to Employee
class Employee
{
public:
Employee();
Employee(string firstName, string lastName, int age, char gender, double employeeNumber);
void ReadEmployee(string firstName, string lastName, int age, char gender, double employeeNumber);
char getGender();
string getFirst();
void Employee::setLast(string lname);
string getLast();
void PrintEmployee();
private:
string LastName;
string FirstName;
int Age;
char Gender;
double EmployeeNumber;
};
typedef Employee DataType;
class SeqList
{
private:
// list storage array and number of current list elements
DataType listitem[MaxListSize];
int size;
public:
// constructor
SeqList(void);
// list access methods
int ListSize(void) const;
int ListEmpty(void) const;
int Find (DataType& item) const;
DataType GetData(int pos) const;
// list modification methods
void Insert(const DataType& item);
void Delete(const DataType& item);
DataType DeleteFront(void);
void ClearList(void);
};
// Class Definition:
// constructor. set size to 0
SeqList::SeqList (void): size(6)
{}
// return number of elements in list
int SeqList::ListSize(void) const
{
return size;
}
// tests for an empty list
int SeqList::ListEmpty(void) const
{
return size == 0;
}
// clears list by setting size to 0
void SeqList::ClearList(void)
{
size = 0;
}
// Take item as key and search the list. return True if item
// is in the list and False otherwise. if found,
// assign the list element to the reference parameter item
bool operator==(Employee A, Employee B)
{
bool isequal = false;
if (A.getLast() == B.getLast())
isequal = true;
return isequal;
}
int SeqList::Find(DataType& item) const
{
int i = 0;
if (ListEmpty())
return 0; // return False when list empty
while (i < size && !(item == listitem[i]))
i++;
if (i < size)
{
item = listitem[i]; // assign list element to item
return 1; // return True
}
else
return 0; // return False
}
// insert item at the rear of the list. terminate the program
// if the list size would exceed MaxListSize.
void SeqList::Insert(const DataType& item)
{
// will an insertion exceed maximum list size allowed?
if (size+1 > MaxListSize)
{
cout << "Maximum list size exceeded" << endl;
exit(1);
}
// index of rear is current value of size. insert at rear
listitem[size] = item;
size++; // increment list size
}
// search for item in the list and delete it if found
void SeqList::Delete(const DataType& item)
{
int i = 0;
// search for item
while (i < size && !(item == listitem[i]))
i++;
if (i < size) // successful if i < size
{
// shift the tail of the list to the left one position
while (i < size-1)
{
listitem[i] = listitem[i+1];
i++;
}
size--; // decrement size
}
}
// delete element at front of list and return its value.
// terminate the program with an error message if the list is empty.
DataType SeqList::DeleteFront(void)
{
DataType frontItem;
// list is empty if size == 0
if (size == 0)
{
cout << "Attempt to delete the front of an empty list!" << endl;
exit(1);
}
frontItem = listitem[0]; // get value from position 0.
Delete(frontItem); // delete the first item and shift terms
return frontItem; // return the original value
}
// return value at position pos in list. if pos is not valid
// list position, teminate program with an error message.
DataType SeqList::GetData(int pos) const
{
// terminate program if pos out of range
if (pos < 0 || pos >= size)
{
cout << "pos is out of range!" << endl;
exit(1);
}
return listitem[pos];
}
Employee::Employee()
{
FirstName = "";
LastName = "";
Age = 0;
/*Gender = "";*/
EmployeeNumber = 0;
};
Employee::Employee(string firstName, string lastName, int age, char gender, double employeeNumber)
{
FirstName = firstName;
LastName = lastName;
Age = age;
Gender = gender;
EmployeeNumber = employeeNumber;
};
void Employee::PrintEmployee()
{
cout << "First Name: " << FirstName << "\n";
cout << "Last Name: " << LastName << "\n";
cout << "Age: " << Age << "\n";
cout << "Gender: " << Gender << "\n";
cout << "Employee Number :" << EmployeeNumber << "\n" << "\n";
};
void Employee::ReadEmployee(string firstName, string lastName, int age, char gender, double employeeNumber)
{
FirstName = firstName;
LastName = lastName;
Age = age;
Gender = gender;
EmployeeNumber = employeeNumber;
};
char Employee::getGender()
{
return Gender;
}
string Employee::getFirst()
{
return FirstName;
}
string Employee::getLast()
{
return LastName;
}
void Employee::setLast(string lname)
{
LastName = lname;
}
Problem in the constructor:
SeqList::SeqList (void): size(6)
size is being initialized as 6.
Other suggestions. Don't put using namespace std; in a header file. Better yet, don't put using namespace std; anywhere.
Why is "using namespace std" considered bad practice?
// constructor. set size to 0
SeqList::SeqList (void): size(6)
{}
This is wrong. Should be so:
// constructor. set size to 0
SeqList::SeqList (void): size(0)
{}