separating C++ code in to multiple files - c++

I hope you are all doing well.
I have the below code which manages a printing queue. I need to separate it into the below files and I dont know how to this. Oddly i've never been asked to do this. Any help you can provide would be greatly appreciated. I am not sure what code goes in which file.
Files I need to separate my code into:
1. heap.h - declaration file for heap.
2. heap.cpp - implementation file for heap.
3. pqtype.h - declaration file for priority queue.
4. pqtype.cpp - implementation file for priority queue.
5. test.cpp - driver file.
My current Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
using namespace std;
struct node
{
int priority;
int jNum;
string jName;
struct node *next;
};
class PriorityQueue
{
private:
node *front;
public:
PriorityQueue()
{
front = NULL;
}
void addJob(string item, int priority, int number)
{
node *temp, *q;
temp = new node;
temp->jName = item;
temp->priority = priority;
temp->jNum = number;
//whether queue is empty
if (front == NULL || priority < front->priority)
{
temp->next = front;
front = temp;
}
else
{
q = front;
while (q->next != NULL && q->next->priority <= priority)
q = q->next;
temp->next = q->next;
q->next = temp;
}
}
void printJob()
{
node *temp;
if (front == NULL)
cout << "There Are No Print Requests In The Queue.\n";
else
{
temp = front;
cout << "\nNow printing Request # " << temp->jNum << " " <<"For "<< temp->jName <<"\n"<< endl;
front = front->next;
free(temp);
}
}
void viewJob()
{
node *ptr;
ptr = front;
if (front == NULL)
cout << "There Are No Print Requests In The Queue\n\n";
else
{
while (ptr != NULL)
{
cout << "Job #: " << ptr->jNum << " " <<"For "<< ptr->jName <<"\n"<< endl;
ptr = ptr->next;
}
}
}
};
int main()
{
int choice, priority;
PriorityQueue pq;
char ch;
string jName;
int number = 0;
cout << "Printing Queue\n" << endl;
do
{
cout << "==============" << endl;
cout << "1. Add Job\n";
cout << "2. Print Job\n";
cout << "3. View Job\n";
cout << "4. Exit\n";
cout << "\nEnter Your Option Now : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Are You A Student (s or S), TA (t or T), Or Instructor (i or I)? ";
cin >> ch;
if (ch == 'i' || ch == 'I')
{
priority = 1;
jName = "Instructor";
cout << "\nJob Successfully Entered.\n\n";
}
else if (ch == 't' || ch == 'T')
{
priority = 2;
jName = "TA";
cout << "\nJob Successfully Entered.\n\n";
}
else if (ch == 's' || ch == 'S')
{
priority = 3;
jName = "Student";
cout << "\nJob Successfully Entered.\n\n";
}
number++;
pq.addJob(jName, priority, number);
break;
case 2:
pq.printJob();
break;
case 3:
pq.viewJob();
break;
case 4:
cout << "\nThank You For Using Printint Queue\nProgram Now Closing...\n\n";
break;
default:
cout << "\nInvalid Choice Selected! \n";
}
}
while (choice != 4);
system("PAUSE");
return 0;
}

Related

Error in my c++ code using linkedlist "Stop working" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
my code stop working in that test case, i think that the error in function Checktables but i'm not sure and i can't fix the error please help me to tun this code correctly.
image of a test case and the error
this is a cpp file with main .cpp
#include"Header.h"
string Name;
string namess;
customer::customer()
{
name = "";
gsize = status = 0;
next = NULL;
}
customer::customer(string name1, int gsize1, int status1)
{
name = name1;
gsize = gsize1;
status = status1;
next = NULL;
}
waitinglist::waitinglist()
{
chairnum =50 ;
totalcustomers = tables = 0;
head = tail = NULL;
}
waitinglist::waitinglist(int val)
{
chairnum = 50;
totalcustomers = 0;
tables = 0;
head = tail = NULL;
}
void waitinglist::change()
{
customer*temp ;
temp = head;
cout << "enter the name: ";
cin >> namess;
while (temp != NULL)
{
if (namess == temp->name)
{
if (temp->status==2)
{
temp->status=1;
cout << "done! " << endl ;
break ;
}
}
else if (namess != temp->name)
{
temp = temp->next;
}
}
if (temp == NULL)
{
cout << "can't found! " << endl;
}
}
void waitinglist::newcustomer()
{
customer*tmp = new customer;
cout << "enter the name: "; cin >> tmp->name;
customer*tmpo=new customer;
tmpo=head ;
while (tmpo != NULL)
{
if (tmp->name != tmpo->name)
{
tmpo = tmpo->next;
}
else if (tmp->name == tmpo->name)
{
cout<<"The Name already exist! " << endl ;
cout << "enter the name: "; cin >> tmp->name;
tmpo=head;
}
}
cout << "enter the group number: "; cin >> tmp->gsize;
cout << "enter the status: "; cin >> tmp->status;
if (head == NULL) // linkedlist is empty
{
head = tail = tmp;
totalcustomers++;
}
else
{
tail->next = tmp;
tail=tail->next;
totalcustomers++;
}
}
void waitinglist::checktables()
{
float c=5.00;
customer*temp=head;
customer*found;
cout<<"enter number of tables: ";
cin >> tables ;
while (tables>=1 && temp!=NULL)
{
int x;
float y;
y=((temp->gsize)/c);
x=(temp->gsize)/c;
if (tables<y)
{
temp=temp->next;
}
else if (tables>=y)
{
if (x==y)
{
tables=tables-x ; // Correct Table!
cout<<temp->name<<endl;
}
else if (x!=y)
{
tables=tables-(x+1);
cout<<temp->name<<endl;
}
found=temp ;
delete found; // Discard
break ;
}
}
}
void waitinglist::displayall()
{
customer *tmp;
tmp = head;
if (tmp == NULL)
{
cout << "Empty!";
}
while (tmp != NULL)
{
cout << "Name: " << tmp->name <<endl;
cout << "group number: " << tmp->gsize << endl;
tmp = tmp->next;
}
cout << endl;
}
void waitinglist::diplaycustomer()
{
customer*tmp;
tmp = head;
cout << "enter the name: ";
cin >> Name;
while (tmp != NULL)
{
if (Name == tmp->name)
{
cout << "the name : " << tmp->name << endl;
cout << "the group size = " << tmp->gsize << endl;
cout << "the status = " << tmp->status << endl;
break;
}
else if (Name != tmp->name)
{
tmp = tmp->next;
}
}
if (tmp == NULL)
{
cout << "can't found!" << endl;
}
}
int main()
{
int choice;
string name1 = "";
int gsize1 = 0;
int status1 = 0;
waitinglist mylist;
cout << "Note: 1 in status means the customer not here and 2 means the customer is here.\n";
cout << "Select your option.\n\n";
cout << "(1) Add a new Customer.\n";
cout << "(2) Display information based on Name.\n";
cout << "(3) List all Names.\n";
cout << "(4) to change the status. \n" ;
cout << "(5) Check tables by name. \n";
cout << "(6) quit. \n";
do
{
cout << "\n";
cout << "Enter your choice: --> ";
cin >> choice;
if (1 <= choice && choice <= 5)
{
switch (choice)
{
case 1:
mylist.newcustomer();
break;
case 2:
mylist.diplaycustomer();
break;
case 3:
mylist.displayall();
break;
case 4:
mylist.change() ;
break;
case 5 :
mylist.checktables();
break;
default:
cout << "Invalid choice. Enter again.\n\n";
break;
}
}
else if (choice>6)
{
cout << "Invalid choice. Enter again.\n\n";
break;
}
} while (choice != 6);
return 0;
}
and this is the header file .h
#include<iostream>
#include<string>
using namespace std;
class customer
{
public:
string name;
int gsize;
int status;
customer* next;
customer();
customer(string,int,int);
};
class waitinglist
{
public:
int tables; //number of occupied tables
int chairnum;
int totalcustomers;
customer*head,*tail;
waitinglist();
waitinglist(int);
void newcustomer();
void diplaycustomer();
void displayall();
void change () ;
void checktables();
};
One error is that your checktables function corrupts your linked list structure by calling delete on one of the nodes:
found = temp;
delete found; // Discard
What you've just done in those lines above is to have a linked list with a broken (invalid) link in it. Any functions that now traverses the list (like displaytables) will now hit the broken link, and things start to go haywire.
To delete a node from a linked list, you have to not just call delete, but adjust the link in waitinglist that used to point to that deleted node and have it point to the next node after the deleted one.
Think of it like a real chain -- if one of the links in the chain needs to be removed, you have to physically remove it, and hook the link before it to the next good link. You didn't do this step.
I won't write the code for that, but this is what you should have seen much earlier in the development of your program. Better yet would have been to write a singly-linked list class that adds and removes nodes correctly first. Test it, and then once it can add and remove nodes successfully without error, then use it in your larger program.

How to implement priority queue in C++?

I am implementing a train boarding system using priority queue. I have the working code but I need to make the following changes..
The priority levels will be : High, Medium and Low. So the passenger should input his/her name and the priority level. The train can have up to 30 passengers.
In the end I will sort the passengers accordingly... Here what I have so far my problem is taking strings as arguments instead of the integers I have now.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
using namespace std;
#define High 1
#define Medium 2
#define Low 3
/*
* Node Declaration
*/
struct node
{
int priority;
int info;
struct node *link;
};
/*
* Class Priority Queue
*/
class Priority_Queue
{
private:
node *front;
public:
Priority_Queue()
{
front = NULL;
}
/*
* Insert into Priority Queue
*/
void insert(int item, int priority)
{
node *tmp, *q;
tmp = new node;
tmp->info = item;
tmp->priority = priority;
if (front == NULL || priority < front->priority)
{
tmp->link = front;
front = tmp;
}
else
{
q = front;
while (q->link != NULL && q->link->priority <= priority)
q = q->link;
tmp->link = q->link;
q->link = tmp;
}
}
/*
* Delete from Priority Queue
*/
void del()
{
node *tmp;
if (front == NULL)
cout << "Queue Underflow\n";
else
{
tmp = front;
cout << "Deleted item is: " << tmp->info << endl;
front = front->link;
free(tmp);
}
}
/*
* Print Priority Queue
*/
void display()
{
node *ptr;
ptr = front;
if (front == NULL)
cout << "Queue is empty\n";
else
{
cout << "Queue is :\n";
cout << "Priority Item\n";
while (ptr != NULL)
{
cout << ptr->priority << " " << ptr->info << endl;
ptr = ptr->link;
}
}
}
};
/*
* Main
*/
int main()
{
int choice, item, priority;
Priority_Queue pq;
do
{
cout << "1.Insert\n";
cout << "2.Delete\n";
cout << "3.Display\n";
cout << "4.Quit\n";
cout << "Enter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Input the item value to be added in the queue : ";
cin >> item;
cout << "Enter its priority : ";
cin >> priority;
pq.insert(item, priority);
break;
case 2:
pq.del();
break;
case 3:
pq.display();
break;
case 4:
break;
default:
cout << "Wrong choice\n";
}
} while (choice != 4);
return 0;
}
I would avoid using string values for the queue and just translate plain-text priorities to the respective integer value, think
int ParsePriority(string plainTextPriority)
{
switch(plainTextPriority) {
case "High": return 1;
case "Medium": return 2;
case "Low": return 3;
}
throw "Unknown priority class";
}
You'll then be able to use the priority values like you did before.
case 1:
cout << "Input the item value to be added in the queue : ";
cin >> item;
cout << "Enter its priority : ";
do {
string plainTextPriority;
cin >> plainTextPriority;
try {
priority = ParsePriority(plainTextPriority)
}
catch {
priority = 0;
cout << "Could not parse the priority, please enter one of High, Medium, Low" << endl;
}
} while (priority == 0);
pq.insert(item, priority);
break;
I added the loop to take the case that a value that does not represent a valid priority has been entered into account.
Here you can use mapping.
int main()
{
int choice, item;
string priority;
map<string,int>m;
m["High"]=1;
m["Low"]=3;
m["Medium"]=2;
Priority_Queue pq;
do
{
cout << "1.Insert\n";
cout << "2.Delete\n";
cout << "3.Display\n";
cout << "4.Quit\n";
cout << "Enter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Input the item value to be added in the queue : ";
cin >> item;
cout << "Enter its priority : ";
cin >> priority;
pq.insert(item, m[priority]);//look change
//... rest of the code will same
and you need to include #include<map> also.
Thank you.

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();
}
};

Suggestions with creating a Menu for Patient Program in C++

So I've basically have most of the programming almost complete. I wanted to add a menu that displays an output. For example, a list of records is created. After it is all entered, I would like for it to display only the patients that smoke or have high blood pressure or high fat diet when selecting a number from the menu. Now I am stuck trying to figure that out but can't seem to wrap my head around it. Any suggestions of how I can get it work? Right now it is only set to display all of the records at once.
//Program Description: An interface program that displays patients records.
#include <iostream>
#include <string>
using namespace std;
struct Node
{
char name[20];
int age;
string smoker;
string hbp;
string hfd;
int points;
Node *ptr;
};
Node *startPtr = NULL;
void getInfo()
{
Node *p, *p2;
p = new Node;
int agePoints;
int smkPoints;
int hbpPoints;
int hfdPoints;
cout << " Please enter the name of the patient : ";
cin >> p->name;
cout << " Please enter the age of the patient : ";
cin >> p->age;
cout << " Is he/she a smoker (y/n) : ";
cin >> p->smoker;
cout << " Does he/she have high blood pressure? (y/n) : ";
cin >> p->hbp;
cout << " Does he/she have a high fat diet? (y/n) : ";
cin >> p->hfd;
cout << endl;
p->ptr = NULL;
// Age point system
if (p-> age > 30) {
agePoints = 3;
}
else if (p->age > 20)
{
agePoints = 2;
}
else
{
agePoints = 1;
}
// Habits Points System
if (p->smoker == "Y" || p->smoker == "y")
{
p->smoker = "Yes";
smkPoints = 4;
}
else
{
p->smoker = "non smoker";
smkPoints = 0;
}
if (p->hbp == "Y" || p->hbp == "y")
{
p->hbp = "High blood pressure";
hbpPoints = 2;
}
else
{
p->hbp = "Normal blood pressure";
hbpPoints = 0;
}
if (p->hfd == "Y" || p->hfd == "y")
{
p->hfd = "High fat diet";
hfdPoints = 1;
}
else
{
p->hfd = "Low fat diet";
hfdPoints = 0;
}
p->points = agePoints + smkPoints + hbpPoints + hfdPoints;
// Set up link to this node
if (startPtr == NULL) {
startPtr = p;
}
else
{
p2 = startPtr;
while (p2->ptr != NULL)
p2 = p2->ptr;
p2->ptr = p;
}
}
void delete_start_node()
{
Node *p;
p = startPtr;
startPtr = startPtr->ptr;
delete p;
}
void delete_end_node()
{
Node *p1, *p2;
if (startPtr == NULL)
cout << "The List is empty!\n";
else
{
p1 = startPtr;
if (p1->ptr == NULL)
{
delete p1;
startPtr = NULL;
}
else
{
while (p1->ptr != NULL)
{
p2 = p1;
p1 = p1->ptr;
}
delete p1;
p1->ptr = NULL;
}
}
}
void disp()
{
Node *p;
p = startPtr;
if (p == NULL)
cout << "Empty List!\n";
while (p != NULL)
{
if (p == NULL)
cout << "Empty List!\n";
cout << " Name : " << p->name << endl;
cout << " Age : " << p->age << endl;
cout << " Smoker : " << p->smoker << endl;
cout << " Blood Pressure : " << p->hbp << endl;
cout << " Fat Diet : " << p->hfd << endl;
cout << " Points : " << p->points << endl;
cout << endl;
p = p->ptr;
}
}
Node* removeptr(Node* prev)
{
if (prev)
{
if (prev->ptr)
{
Node* p = prev->ptr;
prev->ptr = p->ptr;
return p;
}
}
else if (startPtr)
{
Node* p = startPtr;
startPtr = startPtr->ptr;
return p;
}
return NULL;
}
// sort by age in ascending order
void sortAge()
{
Node* startPtr2 = NULL;
while (startPtr)
{
Node* prev = NULL;
Node* curr = startPtr;
Node* prevMax = NULL;
int max = startPtr->age;
while (curr)
{
if (curr->age > max)
{
max = curr->age;
prevMax = prev;
}
prev = curr;
curr = curr->ptr;
}
// Node with the highest age found pass throug the list.
Node* xferNode = removeptr(prevMax);
if (xferNode)
{
xferNode->ptr = startPtr2;
startPtr2 = xferNode;
}
}
startPtr = startPtr2;
}
int main()
{
Node *p;
p = startPtr;
char selection;
do
{
cout << " Patient Menu\n";
cout << " =============================================\n";
cout << " 1. Insert a new record\n";
cout << " 2. List smoker patients\n"; // smoker patient
cout << " 3. List HBP patients\n"; // high blood pressure patient
cout << " 4. List HFD patients\n"; // high fat diet patient
cout << " 5. Delete a patient record by given name\n";
cout << " 6. Exit the program\n";
cout << " =============================================\n";
cout << " Enter your selection: ";
cin >> selection;
cout << endl;
switch (selection)
{
case '1':
getInfo();
break;
case '2':
disp();
break;
case '3':
break;
case '4':
break;
case '5':
break;
case '6':
cout << " Goodbye!\n";
return 0;
break;
default:
break;
}
}while (selection != 6);
/*
disp();
cout << "________________________________________________\n";
sortAge();
disp();*/
system("pause");
return 0;
}
Node *smokers, *hbp, *hfd = NULL;
You could keep a separate linked list for each type - smoker, hbp, hfd and change
void disp()
// to
void disp(Node* linkedList)
and print list given to it
case '2':
disp(smokers);
break;
case '3':
disp(hbp);
break;
case '4':
disp(hfd);
break;
btw, smells like a homework :)

Seg Fault at return statement in function

My program is supposed to convert a prompt from infix to postfix. So far, through a debugger and various other methods, I have located the exact point at which I segfault, but don't understand why.
Here's my code:
Here's itop.h:
using namespace std;
#include <cstdlib>
#include <iostream>
class sNode{
public:
char data;
sNode *next;
};
class stack{
public:
sNode *head;
void push (char);
sNode pop();
int rank(char);
stack()
{
cout << "Initiliazing stack." << endl;
}
};
This is my itop.cpp file:
#include "itop.h"
void stack::push (char a)
{
// cout << "Pushing " << a << endl;
sNode *sn;
sn = new sNode;
sn->data = a;
sn->next = head;
head = sn;
}
sNode stack::pop()
{
// cout << "Popping stack." << endl;
sNode *sn;
sn = head;
head = head->next;
return *sn;
}
int stack::rank(char x)
{
int num = 0;
// cout << "Checking rank." << endl;
if(x == '\0')
{
num = 1;
// cout << "Checking for null" << endl;
return num;
}
else if(x == '+' || x == '-')
{
num = 2;
// cout << "Checking if + or -" << endl;
return num;
// cout << "After return." << endl;
}
else if(x == '*' || x == '/')
{
num = 3;
// cout << "Checking for * or /" << endl;
return num;
}
else
cout << "Error! Input not valid!" << endl;
}
And here's main.cpp:
using namespace std;
#include <iostream>
#include <cstdlib>
#include <cstring>
#include "itop.h"
int main()
{
char *temp1; //Instantiating variables.
char *temp2;
temp1 = new char[20];
temp2 = new char [20];
stack s;
do //Checking commands.
{
cout << "infix_to_postfix> ";
cin >> temp1;
if(strcmp(temp1, "quit") == 0)
{
return 0;
}
if(strcmp(temp1, "convert") != 0)
{
cout << "Error! Invalid command." << endl;
}
cin >> temp2;
if(strcmp(temp1, "convert") == 0)
{
for(int i=0; i<sizeof(temp2); i++)
{
if(isdigit(temp2[i]))
{
cout << atoi(&temp2[i]);
}
else if(s.rank(temp2[i]) < s.rank(s.head->data))
{
sNode temp = s.pop();
cout << temp.data;
}
else
{
s.push(temp2[i]);
}
}
}
else
{
cout << "Error! Command not supported." << endl;
}
}while(strcmp(temp1, "quit") != 0);
return 0;
}
The function is called at
else if(s.rank(temp2[i]) < s.rank(s.head->data))
And the problem is in here:
else if(x == '+' || x == '-')
{
num = 2;
// cout << "Checking if + or -" << endl;
return num;
// cout << "After return." << endl;
}
Specifically right before return num, I get "Segmentation fault (core dumped)" error message. I have used gdb and all I know is that right after "Checking if + or -" I see "$1 = 2". I'm not quite sure what that means, but it is what I want to return.
Thank you for your help.
There are many mistakes in your code. Your stack implementation is wrong. push() for example only sets head over and over again. This results in your stack class being able to ever only hold one element. next is never set to anything, so it contains random garbage. Further down, you have this:
for(int i=0; i<sizeof(temp2); i++)
sizeof(temp2) does not give you the amount of characters of the string temp2 points to. It gives you the size of the pointer temp2 itself. Furthermore, you end up reading s.head from an empty stack, which will be a pointer to random garbage. At that point, all bets are off of course. You can't expect anything else than a crash and burn.
Fix 1:Write a proper constructor.
stack()
{
head=NULL;
cout << "Initiliazing stack." << endl;
}
Fix 2:Write an extra method to check if stack is empty.
int stack::empty()
{
if(head == NULL)
return true;
else
return false;
}
Fix 3:Check if stack empty before using the stack data.
else if(!s.empty() && s.rank(temp2[i]) < s.rank(s.head->data))
{
...
}
Fix 4: Fix the rest of the code logic.