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
I wrote a program using single CLL in order to have the following output:
Main Menu
Create Books CLL
Add book
Search (by Book Name)
Delete Author
Enter your Choice: 1
Enter Book ID: 11223344
Enter Book Name: Programming C++
Enter Author’s Name: Jhone
Node Created
But when i enter the first choice i will enter the book id, book name and then it will start looping without stop! What's wrong with my program?
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node
{
int bid;
char book,author;
struct node *next;
}*last;
class circular_llist
{
public:
void create_node(int id,char bname,char aname);
void add_begin(int id,char bname,char aname);
void delete_element(char author);
void search_element(char name);
void display_list();
circular_llist()
{
last = NULL;
}
};
int main()
{
int choice, bid, position;
char name,author;
circular_llist cl;
while (1)
{
cout<<endl<<"Main Menu:"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at beginning"<<endl;
cout<<"3.Delete"<<endl;
cout<<"4.Search"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the Book ID: ";
cin>>bid;
cout<<"Enter the Book Name: ";
cin>>name;
cout<<"Enter the Book Author: ";
cin>>author;
cl.create_node(bid,name,author);
cout<<endl;
break;
case 2:
cout<<"Enter the Book ID: ";
cin>>bid;
cout<<"Enter the Book Name: ";
cin>>name;
cout<<"Enter the Book Author: ";
cin>>author;
cl.add_begin(bid,name,author);
cout<<endl;
break;
case 3:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the Author name for deletion: ";
cin>>author;
cl.delete_element(author);
cout<<endl;
break;
case 4:
if (last == NULL)
{
cout<<"List Empty!! Can't search"<<endl;
break;
}
cout<<"Enter Book Name: ";
cin>>name;
cl.search_element(name);
cout<<endl;
break;
case 5:
cl.display_list();
break;
case 6:
exit(1);
}
}
return 0;
}
void circular_llist::create_node(int id,char bname,char aname)
{
struct node *temp;
temp = new(struct node);
temp->bid = id;
temp->book = bname;
temp->author = aname;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}
void circular_llist::add_begin(int id,char bname,char aname)
{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->bid = id;
temp->book = bname;
temp->author = aname;
temp->next = last->next;
last->next = temp;
}
void circular_llist::delete_element(char author)
{
struct node *temp, *s;
s = last->next;
if (last->next == last && last->author == author)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->author == author) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->author == author)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<author;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
if (s->next->author == author)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<author<<" not found in the list"<<endl;
}
void circular_llist::search_element(char name)
{
struct node *s;
int counter = 0;
s = last->next;
while (s != last)
{
counter++;
if (s->book == name)
{
cout<<"Element "<<name;
cout<<" found at position "<<counter<<endl;
return;
}
s = s->next;
}
if (s->book == name)
{
counter++;
cout<<"Element "<<name;
cout<<" found at position "<<counter<<endl;
return;
}
cout<<"Element "<<name<<" not found in the list"<<endl;
}
void circular_llist::display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Books List: "<<endl;
while (s != last)
{
cout<<s->bid<<"\n"<<s->book<<"\n"<<s->author<<"\n"<<endl;
s = s->next;
}
cout<<s->bid<<"\n"<<s->book<<"\n"<<s->author<<"\n"<<endl;
}
When you read single characters (like you do with name and author) you really read only single character. And you enter multiple characters for those fields, meaning that the first input (to name) will read the fist character of the name, and the second input (to author) will read the second character of the name. That will leave quite a few characters in the input buffer, and attempting to read anything but characters or strings will fail, but you don't check for these failures so you end up with just looping over and over again trying to read e.g. a number and failing.
Simplest solution? Begin with using std::string for strings, and continue with reading multiple-word entries using std::getline.
The problem is how you input author and book name, e.g., cin>>name. This reads only the first word from the input and the rest of the name (if it has spaces) is left in the input buffer. Next you try to read the menu choice number and it will fail because the next character in the buffer is the first character of the second word of the name of the book, or such. I suggest that you replace your cin >> name with std::getline.
UPDATE
Oh! I have missed that you actually input only a single character...
Related
im trying to implement both queue and stack in my mini project. Customer will enter nodes into stack and the seller will sort the nodes from stack and put them into queue. I want to sort nodes from a stack based on college name, where all nodes with college = "kdoj" will get into the queue first then followed by all nodes with college = "kdse". The problem is i have tried doing the sorting with 2 (for loop) and i dont know why only 2 nodes get into the queue when i have more than 2 nodes in the stack. i am not sure where is the problem and been stuck here for a while :(.
This is the input example:
name : david
ic num: 123
phone num: 123
college: kdse
quantity: 1
size: m
name : jojo
ic num: 123
phone num: 123
college: kdse
quantity: 1
size: m
name : zoro
ic num: 123
phone num: 123
college: kdoj
quantity: 1
size: m
This is the runnable code.
The problem will occur when you sort the list in seller menu after entering the data.
#include <iostream>
#include <cstring>
#include<iomanip>
#include <conio.h>
#include<string>
using namespace std;
//nodes
struct customerNode {
string name, id, college;
int phoneNum,quantity;
char size;
public:
customerNode* next;
customerNode(string name, string id, int phoneNum,string college, int quantity, char size)
{
name = name;
id = id;
phoneNum = phoneNum;
college = college;
quantity = quantity;
size = size;
next = NULL;
}
};
//class customer
class Customer{
public:
customerNode *head = NULL;
bool isEmpty(){
return(head == NULL);
}
void pushStack(string name, string id, int phoneNum, string college, int quantity, char size){
customerNode *newnode = new customerNode(name,id,phoneNum,college,quantity,size);
newnode->name = name;
newnode->id= id;
newnode->phoneNum = phoneNum;
newnode->college = college;
newnode->quantity = quantity;
newnode->size = size;
if(isEmpty()){
newnode->next = head;
head = newnode;
cout<<endl<<"created new stack."<<endl;
}
else{
newnode->next = head;
head = newnode;
cout<<endl<<"added node into a stack."<<endl;
}
}
//pop out node from stack
void popStack(){
customerNode *temp;
temp = head; //temp variable
head = temp->next;
temp->next = NULL;
cout<<endl<<"Order has been deleted!";
}
//push node into stack
void enterOrder(){
int phoneNum, quantity;
char size;
string name, id, college;
cout<<endl<<"\tADDING YOUR ORDER.\n";
cout<<"\tName: ";
cin.ignore();
getline(cin,name);
cout<<"\tIC Num: ";
cin>>id;
cout<<"\tPhone Number: ";
cin>>phoneNum;
cout<<"\tCollege name: ";
cin>>college;
cout<<"\tQuantity: ";
cin>>quantity;
cout<<"\tSize (S/M/L/XL): ";
cin>>size;
pushStack(name, id, phoneNum,college, quantity, size);
cin.get();
}
//see order and trigger popout funct
void deleteorder(){
char choice;
cout<<"YOUR ODER."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
stackTop();
cout<<endl;
cout<<endl<<"Confirm to delete?: ";
cin>>choice;
if(choice == 'y' || choice == 'Y'){
popStack();
}
}
//display node at the top
void stackTop(){
customerNode *check;
if(!isEmpty()){
check = head;
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
int getNumberNodes(){
customerNode *check;
check = head;
int counter = 0;
while(check!= NULL){
counter++;
check = check->next;
}
return counter;
}
};
//Customer main menu
void customerMenu(Customer &c){
int choice;
do{cout
<<endl<<"CUSTOMER MENU"
<<endl<<"Please choose your task."
<<endl<<"1. Insert Order"
<<endl<<"2. Delete Order"
<<endl<<"3. Check Order"
<<endl<<"4. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
//customer task
switch(choice){
case 1: c.enterOrder();
break;
case 2: c.deleteorder();
break;
case 3:
cout<<"\nYOUR ODER."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
c.stackTop();
cout<<endl;
break;
}
}while(choice != 4);
};
//SELLER CLASS
class Seller{
string id;
string password;
public:
customerNode *backPtr, *frontPtr;
//constructor seller
Seller(){
id = "12345";
password = "12345";
backPtr = NULL;
frontPtr = NULL;
}
//check queue empty
bool queueEmpty(){
return (backPtr == NULL && frontPtr == NULL);
}
//display all nodes in stack
void getStack(Customer &c){
customerNode *check;
if(!c.isEmpty()){
check = c.head;
while(check!=NULL){
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
check=check->next;
}
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
//will trigger getStack()
void displayStack(Customer &c){
cout<<"\nCUSTOMER FULL ORDERLIST."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
getStack(c);
cout<<endl;
}
//display all nodes in queue
void getQueue(){
customerNode *check;
if(!queueEmpty()){
check = frontPtr;
while(check!=NULL){
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
check=check->next;
}
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
//display node in queue
void displayQueue(){
cout<<"\nSORTED CUSTOMER FULL ORDERLIST."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
getQueue();
cout<<endl;
}
//insert queuee
void insertQueue(customerNode *newNode){
if(!queueEmpty()){
newNode->next = NULL;
backPtr->next = newNode;
backPtr = newNode;
cout<<endl<<"inserted node into queue."<<endl;
}
else{
frontPtr = newNode;
backPtr = newNode;
}
}
void sortOrder(Customer &c){
for(customerNode *node = c.head; node!=NULL; node = node->next){
if(node->college == "kdoj"){
cout<<endl<<node->college;
insertQueue(node);
}
}
for(customerNode *node = c.head; node!=NULL; node = node->next){
if(node->college == "kdse"){
cout<<endl<<node->college;
insertQueue(node);
}
}
displayQueue();
}
};
//seller main menu
void sellerMenu(Customer &c, Seller &s){
int choice;
do{cout
<<endl<<"SELLER MENU"
<<endl<<"Please choose your task."
<<endl<<"1. Display OrderList"
<<endl<<"2. Sort OrderList"
<<endl<<"4. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
//choose task
switch(choice){
case 1: s.displayStack(c);
break;
case 2: s.sortOrder(c);
break;
case 3:
break;
}
}while(choice != 4);
}
void menu(Customer &c, Seller &s){ //main menu function
int choice;
do{
cout
<<endl<<"Welcome to HotspotPrinting!"
<<endl<<"Please choose your role."
<<endl<<"1. Customer"
<<endl<<"2. Seller"
<<endl<<"3. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
switch(choice){
case 1: customerMenu(c);
break;
case 2: sellerMenu(c,s);
break;
}
}while(choice != 3);
}
int main()
{
Customer c;
Seller s;
menu(c,s);
cout<<endl<<"Thank You For Using Our Service :)!";
return 0;
}
your problem is that customer node records exist in two containers, your queue and a list. But you only have one next pointer, when you insert a customer into the queue you set its next pointer to null, this destroys the linkage in the customer list.
If you need to have the same object in 2 containers then use shared_ptr in standard containers, like std::list and std::queue
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 3 years ago.
Improve this question
I wrote a program which should to insert elements in the list compare with their costs, but it doesn't work. I enter one element and then program doesn't work. And I can't understand what's wrong.
here is an exactly the exercise:
Modify the list, so elements on the list are ordered by price. New items added to the list should be inserted into the right place
#include <iostream>
#include <string>
using namespace std;
typedef struct listt
{
string name;
float price;
struct listt *next;
}listt;
typedef listt* listPtr;
void insertt(listPtr *, string, float);
void printList(listPtr);
void instruct();
int main()
{
unsigned int choice;
float costs;
string itemName;
listPtr head = NULL;
instruct();
cin >> choice;
while(choice != 3)
{
switch(choice)
{
case 1:
cout << "Please enter the name of the item:" << endl;
cin >> itemName;
cout << "Please enter the cost of item: " <<endl;
cin >> costs;
insertt(&head, itemName, costs);
break;
case 2:
printList(head);
break;
}
cout<<"Choose the operation\n";
cin >> choice;
}
cout<<"end of operation";
return 0;
}
void instruct(void)
{
cout<<"Choose the operation\n" << "1.Fill the list\n" << "2.Print the list\n" << "3.End operation\n";
}
void insertt(listPtr *itemList, string nm, float cst)
{
listPtr previousPt;
listPtr currentPt;
listPtr newPtr;
if(newPtr != NULL){
newPtr->name = nm;
newPtr->price = cst;
newPtr->next = *itemList;
}
previousPt = NULL;
currentPt = *itemList;
while(currentPt != NULL && cst > currentPt->price )
{
previousPt = currentPt;
currentPt = currentPt->next;
}
if(currentPt == NULL)
{
newPtr->next = *itemList;
*itemList = newPtr;
} else{
previousPt->next = newPtr;
newPtr->next = currentPt;
}
}
void printList(listPtr hh)
{
while(hh->next != NULL)
{
cout << hh->name <<" " << hh->price<< endl;
hh = hh->next;
}
}
in insertt :
void insertt(listPtr *itemList, string nm, float cst)
{
listPtr previousPt;
listPtr currentPt;
listPtr newPtr;
if(newPtr != NULL){
newPtr->name = nm;
newPtr->price = cst;
newPtr->next = *itemList;
}
newPtr is not initialized but you compare its value to NULL then may be modify an unknown block of memory, this is an undefined behavior
replace listPtr newPtr; by listPtr newPtr = new listt;
That comes because of typedef listt* listPtr; hidding the pointer, do not define typedef hiding pointer, this is always a source of problem
Your way to insert the new cell is wrong, for instance if the second insert cell as a lower price than the first you have an illegal memory access. A working solution is :
void insertt(listt ** itemList, string nm, float cst)
{
listt * newCell = new listt;
newCell->name = nm;
newCell->price = cst;
newCell->next = nullptr;
if (*itemList == nullptr)
*itemList = newCell;
else {
for (;;) {
if (cst < (*itemList)->price) {
newCell->next = *itemList;
*itemList = newCell;
return;
}
if ((*itemList)->next == nullptr) {
(*itemList)->next = newCell;
return;
}
itemList = &(*itemList)->next;
}
}
}
Note printList is erroned because the last element is never print, replace
while(hh->next != NULL)
by
while(hh != NULL)
or better
while(hh != nullptr)
Your struct listt is defined like in C
You need also to check your input are valid, your cin >> x; must be if (! (cin >> x)) { ..error management .. }
I am sorry for posting the entire code, but I am having a real hard time while getting specific data from each node and transfer the entire data to a whole new node in the function named "Enqueue". I tried adding a watcher to see what my program is doing, it gets stuck in the "Enqueue" function at the if-statement "if (front == NULL && rear == NULL)". Can someone please point my problem what is my mistake? Thanks.
#include <iostream>
#include <string>
using namespace std;
int numb_persons_category1 = 0;
int numb_persons_category2 = 0;
int numb_persons_category0 = 0;
class Queue
{
struct node
{
string name, date;
int room;
node *next;
};
node *front;
node *rear;
public:
Queue()
{
front = NULL;
rear = NULL;
}
void Enqueue(string _name, string _date, int _room)
{
node *p = new node;
p -> name = _name;
p -> date = _date;
p -> room = _room;
p -> next = NULL;
if (front == NULL && rear == NULL)
{
front = rear = p;
return;
}
rear->next = p;
rear = p;
}
void Dequeue()
{
node *temp = front;
if (front == NULL)
return;
if (front == rear)
{
front = rear = NULL;
}
else
{
front = front->next;
}
free(temp);
}
int Front()
{
if(front == NULL)
{
cout<<"Queue is empty\n";
}
return front->room;
}
bool IsEmpty()
{
return front == NULL;
}
void populate(Queue *any_queue, int _room, int numb_persons_category)
{
node *any_node = front;
while(any_node != NULL)
{
if (_room == 1)
{
any_queue->Enqueue(any_node->name, any_node->date, any_node->room);
cout<<"Name: "<<any_node->name<<endl;
cout<<"Last Visit: "<<any_node->date<<endl;
cout<<"Room: "<<any_node->room<<endl;
cout<<any_node->name<<" must be sent to "<<_room<<endl;
numb_persons_category++;
}
else if (_room == 2)
{
any_queue->Enqueue(any_node->name, any_node->date, any_node->room);
cout<<"Name: "<<any_node->name<<endl;
cout<<"Last Visit: "<<any_node->date<<endl;
cout<<"Room: "<<any_node->room<<endl;
cout<<any_node->name<<" must be sent to "<<_room<<endl;
numb_persons_category++;
}
else if (_room == 0)
{
any_queue->Enqueue(any_node->name, any_node->date, any_node->room);
cout<<"Name: "<<any_node->name<<endl;
cout<<"Last Visit: "<<any_node->date<<endl;
cout<<"Room: "<<any_node->room<<endl;
cout<<any_node->name<<" must be sent to "<<_room<<endl;
numb_persons_category++;
}
cout<<endl<<endl;
any_node = any_node->next;
}
}
void Print()
{
//If you are using Windows, uncomment the line of code that says system("cls");
//I have added the line of code as comment since I am using a non-Windows machine.
//system("cls");
//It doesn't matter if you don't really care about the output of my program anyway
//It works in both cases.. But I am just trying to clear things up for the user :)
node* temp = front;
while(temp != NULL) {
cout<<"Name: "<<temp->name<<endl;
cout<<"Last Visit: "<<temp->date<<endl;
cout<<"Room: "<<temp->room<<endl;
cout<<endl;
temp = temp->next;
}
cout<<endl;
cout<<"Number of patients in category 0: "<<numb_persons_category0<<endl;
cout<<"Number of patients in category 1: "<<numb_persons_category1<<endl;
cout<<"Number of patients in category 2: "<<numb_persons_category2<<endl;
}
};
Queue *obj_category1;
Queue *obj_category2;
Queue *obj_category0;
void room(string _name, string _date, int _room, Queue *obj)
{
switch (_room)
{
case 1:
obj->populate(obj_category1, _room, numb_persons_category1);
break;
case 2:
obj->populate(obj_category2, _room, numb_persons_category2);
cout<<_name<<" must be sent to "<<_room<<endl;
numb_persons_category2++;
break;
case 0:
obj->populate(obj_category0, _room, numb_persons_category0);
cout<<_name<<" must be sent to "<<_room<<endl;
numb_persons_category0++;
break;
default:
cout<<"Room is unavailable!\n\n";
}
}
int main()
{
Queue *obj = new Queue();
int room_number;
string name, date;
char user_visit;
char run = 'y';
while (run == 'y')
{
cout<<"Enter name: ";
cin>>name;
cout<<"Is this your first visit? (Y/N): ";
cin>>user_visit;
if (user_visit == 'n')
{
cout<<"Enter your last visit (MM/DD/YY): ";
cin>>date;
}
else
{
date = "0/0/0";
}
cout<<"Enter room: ";
cin>>room_number;
cout<<"\n\n\n";
obj->Enqueue(name, date, room_number);
room(name, date, room_number, obj);
cout<<"Continue? (Y/N): ";
cin>>run;
}
return 0;
}
You are allocating nodes with new and deallocating them with free.
At least that's one of the bugs, there might be more. Try stepping
through
your code with a debugger.
note; new goes with delete, and is preferable in C++
malloc goes with free and is C-style
First, please indent the entire program code, not only the nested blocks.
Second, you have:
Queue *obj_category1; // which is null as global var initialized by default
obj->populate(obj_category1, _room, numb_persons_category1); // here you pass that null pointer and then it is accessed in the line the debugger complaining about
And yes, 'new' should be matched with 'delete' not 'free' as it was correctly pointed out already. But that is not the reason for specific error and will trigger the error if specific destructor not called. That is not nice in this case but not lethal.
good day. i have a problem with my program. this is designed for small clinics to basically
record the patients information for an appointment. so here is my problem, at first it was
working but whenever im going to input infos for the 3rd patient(3rd node), after inputting
the name it will go on an error. this is a queue. `
#include <iostream>
using namespace std;
struct clnc_hrs
{
std:: string name;
std:: string symptms;
int age;
int cont_num;
clnc_hrs *next;
};
class List{
private:
clnc_hrs *rear;
clnc_hrs *front;
public:
List();
void BookAppointment();
void DeletePrevious();
void DisplaySchedule();
};
List::List(){
rear = NULL;
front = NULL;
}
void List::BookAppointment ()
{
std:: string N;
std:: string S;
int A;
int CN;
clnc_hrs *newnode = (clnc_hrs*)malloc(sizeof(clnc_hrs));
fflush(stdin);
cout<<"enter name of the patient:";
std::getline(cin, N);
newnode->name = N;
fflush(stdin);
cout<<"enter age of the patient:";
cin>>A;
newnode->age = A;
fflush(stdin);
cout<<"enter contact number of the patient:";
cin>>CN;
newnode->cont_num = CN;
fflush(stdin);
cout<<"enter the complaints or symptoms of the patient:";
std::getline(cin, S);
newnode->symptms = S;
newnode->next = NULL;
if(front == NULL)
{
fflush(stdin);
front = newnode;
fflush(stdin);
}
else
{
fflush(stdin);
rear->next = newnode;
fflush(stdin);
}
rear = newnode;
}
void List::DisplaySchedule ()
{
clnc_hrs *disp = (clnc_hrs*)malloc(sizeof(clnc_hrs));
disp = front;
if(front == NULL)
{
cout<<"there's no appointment for today"<<endl;
}
else
{
while(disp != NULL)
{
cout<<endl;
cout<<"name:"<<disp->name<<endl;
cout<<"age:"<<disp->age<<endl;
cout<<"contact number:"<<disp->cont_num<<endl;
cout<<"symptoms/complaints:"<<disp->symptms<<endl;
cout<<endl;
disp = disp->next;
}
}
}
void List::DeletePrevious()
{
clnc_hrs *newnode = (clnc_hrs*)malloc(sizeof(clnc_hrs));
if(front == NULL)
{
cout<<"no appointments today"<<endl;
}
else
{
newnode = front;
front = front->next;
cout<<"The previous patient is: "<<endl;
cout<<newnode->name<<endl;
cout<<newnode->age<<endl;
cout<<newnode->cont_num<<endl;
cout<<newnode->symptms<<endl;
delete newnode;
}
}
int main ()
{
List list;
int ans;
while(true)
{
cout<<"press 1 for booking an appointment\npress 2 to delete previous patients info \npress 3 for display"<<endl;
cin>>ans;
if(ans == 1)
{
list.BookAppointment();
}
else if(ans == 2)
{
list.DeletePrevious();
}
else if(ans == 3)
{
list.DisplaySchedule();
}
}
system("pause");
}
`
i hope someone here can help me. i am using dev c++ 4.9.9.2
As you say this in not homework then just use STL - i.e. http://www.cplusplus.com/reference/queue/queue/
All the bits'n'bobs are done for you
Don't use malloc in a C++ program, it doesn't construct C++ objects correctly, use new instead.
clnc_hrs *newnode = new clnc_hrs();
You might have other errors but this is the first one.
cout<<"enter name of the patient:";
std::getline(cin, N);
newnode->name = N;
is not wrong, but just a bit wasteful. This is simpler
cout<<"enter name of the patient:";
std::getline(cin, newnode->name);
same for all you other inputs.
fflush(stdin);
is implementation defined behaviour. fflush only has defined behaviour on output streams not input streams. You seem to be using fllush(stdin); as some sort of magic incantation that you hope will solve your problems. Avoid that kind of thinking. Learn what the code you write really does. In this case you should remove all calls to fflush(stdin);.
I have made a Student record system in c++ using the concept of linked list. The program will take the student id, name and marks for 3 different exams. Then it will calculate the aggregate percentage based on those exams marks and display the relevant message according to the aggregate percentage. The program is running without any errors.
But I want student id to be unique. For example, if a user inputs a student id which has been already assigned to previous student than it will show a message that "please enter a different id."
How would I do that. Any help will be appreciated.
struct student
{
int id;
char name[MAX];
string status;
double aggr;
int matric_marks, inter_marks, entryTest_marks;
};
struct node
{
struct student *data;
struct node *next;
node()
{
data = 0;
next = NULL;
}
};
struct student *readStudent()
{
clearWindow();
struct student *stdnt = new student;
gotoxy(33,8);cout<<"Student ID: ";
while(!(cin >> stdnt->id) || cin.peek() != '\n')
{
char ch;
cin.clear();
cout << "sorry";
while(cin.get(ch) && ch != '\n');
}
cin.ignore();
gotoxy(33,10);cout<<"Student Name: ";
cin.getline(stdnt->name, 50);
gotoxy(33,12);cout<<"Enter Matriculation Marks: ";
cin>>(stdnt->matric_marks);
gotoxy(33,14);cout<<"Enter Intermediate Marks: ";
cin>>(stdnt->inter_marks);
gotoxy(33,16);cout<<"Enter Entry Test Marks: ";
cin>>(stdnt->entryTest_marks);
stdnt->aggr = calculate_aggregiate(stdnt);
gotoxy(33,18);cout<<"Student Aggregate Marks: "<< stdnt->aggr;
if (stdnt->aggr >= 70)
{
gotoxy(33,20);cout<<"Student Registered In Electrical Engg";
}
else if (stdnt->aggr >= 60)
{
gotoxy(33,22);cout<<"Student Registered In Mechanical Engg";
}
else if (stdnt->aggr >=50)
{
gotoxy(33,24);cout<<"Student Registered In Computer Science";
}
else
{
gotoxy(33,20);cout<<"Sorry! The Student Doesnt Qualify";
}
return stdnt;
}
struct node *createDatabase(int size)
{
int i = 0;
struct node *head = NULL;
struct node *last = NULL;
for(i = 0; i < size; i++)
{
struct student *stdnt = readStudent();
struct node * current = new node;
current->data = stdnt;
current->next = NULL;
if(last)
last->next = current;
else
head = current;
last = current;
}
return head;
}
struct node *InsertRecord(struct node *head)
{
struct node *record = new node;
struct student *stdnt = readStudent();
record->data=stdnt;
record->next=head;
return record;
}
double calculate_aggregiate(struct student *stud)
{
student *stdnt = stud;
double aggr;
aggr = stdnt->matric_marks * 10/100 + stdnt->inter_marks * 50/100 +
stdnt->entryTest_marks * 40/100;
return aggr;
}
struct node *DeleteRecord(struct node *head)
{
clearWindow();
struct node *curr,*prev, *temp;
int tdata;
if(head==NULL)
{
gotoxy(33,10);cout<<"NO RECORDS TO DELETE......!";
}
else
{
gotoxy(33,10);cout<<"Enter Student ID To Be Deleted: ";
cin>>tdata;
prev=curr=head;
while((curr!=NULL)&&(curr->data->id!=tdata))
{
prev=curr;
curr=curr->next;
}
if(curr==NULL)
{
gotoxy(33,12);cout<<"The Requested ID Is Not Found...!";
}
else if(curr==head)
{
head=head->next;
gotoxy(33,12);cout<<"DATA DELETED....!";
}
else
{
prev->next=curr->next;
if(curr->next==NULL)
{
temp=prev;
}
gotoxy(33,12);cout<<"DATA DELETED....!"<<tdata;
}
delete(curr);
}
return head;
}
void ModifyRecord(struct node *head)
{
clearWindow();
int ch, sid;
struct node *current;
struct student *stdnt;
if (head==NULL)
{
gotoxy(33,8);cout<<"NO RECORD TO MODIFY..!";
}
else
{
gotoxy(33,8);cout<<"Enter Student ID To Modify: ";
cin>>sid;
current=head;
while((current!=NULL) && (current->data->id!=sid))
{
current=current->next;
}
if (current==NULL)
{
gotoxy(33,10);cout<<"The Requested ID is Not Found";
}
else if(current->data->id==sid)
{
gotoxy(33,10);cout<<"What Do You Want To Modify";
gotoxy(33,12);cout<<"1. Student's Name";
gotoxy(33,14);cout<<"2. Student's Matric Marks";
gotoxy(33,16);cout<<"3. Student's Intermediate Marks";
gotoxy(33,18);cout<<"4. Student's Entry Test Marks";
gotoxy(33,20);cout<<"Enter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1 : gotoxy(33,22);cout<<"Enter New Name: ";
cin.getline(current->data->name, 50);break;
case 2 : gotoxy(33,22);cout<<"Enter New Matric Marks: ";
cin>>(current->data->matric_marks);break;
case 3 : gotoxy(33,22);cout<<"Enter New Intermediate Marks: ";
cin>>(current->data->inter_marks);break;
case 4 : gotoxy(33,22);cout<<"Enter New Entry Test Marks: ";
cin>>(current->data->entryTest_marks);break;
current->data->aggr = current->data->matric_marks * 10/100 + current->data- >inter_marks * 50/100 +
current->data->entryTest_marks * 40/100;
}
gotoxy(33,24);cout<<"RECORD MODIFIED....!";
}
}
}
void SearchRecord(struct node *head)
{
clearWindow();
int s_id;
struct node *current;
if (head==NULL)
{
gotoxy(33,8);cout<<"NO RECORD TO SEARCH..!";
}
else
{
gotoxy(33,8);cout<<"Enter Student ID To Be Searched: ";
cin>>s_id;
current=head;
while ((current!=NULL) && (current->data->id!=s_id))
{
current=current->next;
}
if (current==NULL)
{
gotoxy(33,10);cout<<"The Requested ID is Not Found";
}
else if (current->data->id==s_id)
{
gotoxy(33,10);cout<<"Student ID: "<<current->data->id;
gotoxy(33,12);cout<<"Student Name: "<<current->data->name;
gotoxy(33,14);cout<<"Student Matric Marks: "<<current->data->matric_marks;
gotoxy(33,16);cout<<"Student Intermediate Marks: "<<current->data - >inter_marks;
gotoxy(33,18);cout<<"Student Entry Test Marks: "<<current->data- >entryTest_marks;
gotoxy(33,20);cout<<"Student Aggregate Marks: "<<current->data->aggr;
if (current->data->aggr >= 70)
{
gotoxy(33,22);cout<<"Student Registered In Electrical Engg";
}
else if (current->data->aggr >= 60)
{
gotoxy(33,22);cout<<"Student Registered In Mechanical Engg";
}
else if (current->data->aggr >=50)
{
gotoxy(33,22);cout<<"Student Registered In Computer Science";
}
else
{
gotoxy(33,22);cout<<"Sorry! The Student Doesnt Qualify";
}
}
}
}
void print(struct node *head)
{
clearWindow_p();
struct node *current = head;
if (head == NULL)
{
gotoxy(33,8);cout<<"No Student Registered Yet......!";
}
else
{
cout<<"\n\t\t\t\t\tSTUDENTS STATISTICS";
while(current)
{
struct student *stdnt = current->data;
cout<<"\n\t\t\t\t\t-------------------------------- ";
cout<<"\n\t\t\t\t\tStudent ID :"<<stdnt->id;
cout<<"\n\t\t\t\t\tStudent Name :"<<stdnt->name;
cout<<"\n\t\t\t\t\tMatric Marks :"<<stdnt->matric_marks;
cout<<"\n\t\t\t\t\tIntermediate Marks :"<<stdnt->inter_marks;
cout<<"\n\t\t\t\t\tEntry Test Marks: "<<stdnt->entryTest_marks;
cout<<"\n\t\t\t\t\tAggregate: "<<stdnt->aggr;
if (stdnt->aggr >= 70)
{
cout<<"\n\t\t\t\t\tStudent Registered In Electrical Engg";
}
else if (stdnt->aggr >= 60)
{
cout<<"\n\t\t\t\t\tStudent Registered In Mechanical Engg";
}
else if (stdnt->aggr >=50)
{
cout<<"\n\t\t\t\t\tStudent Registered In Computer Science";
}
else
{
cout<<"\n\t\t\t\t\tSorry! The Student Doesnt Qualify";
}
current=current->next;
}
cout<<"\n\t\t\t\t\t--------------------------------";
}
}
int compareStudents(struct student *left, struct student *right)
{
return strcmp(left->name, right->name);
}
struct node *sort(struct node *head)
{
//using bubble sort
int swapped = 0;
do
{
swapped = 0;
struct node *current = head;
struct node *previous = NULL;
while(current && current->next)
{
if(compareStudents(current->data, current->next->data) > 0)
{
//swap here
struct node *next = current->next;
if(previous)
{
previous->next = next;
}
else
{
head = next;
}
current->next = next->next;
previous = next;
previous->next = current;
swapped = 1;
}
else
{
previous = current;
current = current->next;
}
}
} while(swapped);
return head;
}
int main()
{
system("color f0");
window();
SetColor(28);
int total,i,choice;
int x = 2;
struct node *head;
head=NULL;
do
{
menu:
gotoxy(x, 8);cout<<"1.Create a Record File";
gotoxy(x, 10);cout<<"2.Insert Student's Record";
gotoxy(x, 12);cout<<"3.Modify Student's Record";
gotoxy(x, 14);cout<<"4.Delete Student's Record";
gotoxy(x, 16);cout<<"5.Search Student's Record";
gotoxy(x, 18);cout<<"6.Print All Records";
gotoxy(x, 20);cout<<"7.Sort According To Names";
gotoxy(x, 22);cout<<"8.Clear The Screen";
gotoxy(x, 24);cout<<"9.Exit";
gotoxy(x, 26);cout<<"Enter your choice";
cout<<" [ ]\b\b";
cin>>choice;
switch(choice)
{
case 1:
clearWindow();
gotoxy(33, 8);cout<<"How Many Students Do You Want To Register: ";
cin>>total;
head=createDatabase(total);
break;
case 2:
head=InsertRecord(head);
break;
case 3:
ModifyRecord(head);
break;
case 4:
DeleteRecord(head);
break;
case 5:
SearchRecord(head);
break;
case 6:
print(head);
break;
case 7:
sort(head);
print(head);
break;
case 8:
main();
break;
default: gotoxy(33,8);cout<<"INVALID OPTION";
}
}while(choice!=9);
getch();
return 0;
}
Since you are using C++, you should take advantage of the built-in types. If there is only one student with a given ID, use the std::map<> template. For example:
struct student
{
char name[MAX];
string status;
double aggr;
int matric_marks, inter_marks, entryTest_marks;
};
map<int, student> students;
then, to traverse students:
for (auto i = students.begin(); i != students.end(); ++i) {
int studentId = i->first;
student& student = i->second;
student.aggr = ...
}
(auto is C++11, not all compilers enable it by default IIRC. See here.)
If You know the range of student ids , and it is within a feasible range of memory , you can use a UsedId[] array.
If the range is too big too be held , use a Hashmap ,(MAP in c++) .
I would probably implement something called FindRecordByID.
struct student *FindRecordByID(struct node *head, int id) {
for(; head != NULL; head = head->next)
if (head->data->id == id)
return head->data;
return NULL;
}
Then when you do your create_new_student routine, you could use that to verify that the given ID is not already used.