Debugging C++ file - c++

I am getting this error main.cpp:23:5: error: ‘Department’ does not name a type
/*
* File: main.cpp
* Author: anonymous
*
* Created on May 11, 2015, 9:44 PM
*/
#include <cstdlib>
#include <iostream>
using namespace std;
class College{
public :
string name; //for name of the college
int numOfColleges;
int numDepartments; //number of departments in this college
Department* dep; //this will point to the department in this college
College* next; //the next pointer to point to the next college
College(){
name =" ";
numDepartments=0 ;
dep = NULL;
next=NULL;}
College (string n, int numD ){name=n ;next=NULL;}
void Print(){
cout<<name<<"\n";
}
};
class Department
{
public:
string name;
int numOfStudents;
Department* next;
Department(){name[0] ; numOfStudents=0 ; next=NULL ;}
Department( string n , int numS){ name =" "; n ;numOfStudents = numS ; next=NULL;}
void Print(){cout<<name<<" "<<numOfStudents;}
};
void AddCollege(College *head)
{
string n;
int numD;
cout<<"Enter the name of the College : ";
cin>>n;
cout<<"Enter the number of Departments : ";
cin>>numD;
College* tmp = new College(n,numD);
if(!head)
{
head=tmp;
return;
}
College * t=head;
while(t->next) t=t->next;
t->next=tmp;
cout<<"college added";
}
void DeleteCollege(College*&head)
{
string name;
cout<<"enter name of college:";
cin>>name;
if((!head)||(!head->next && head->name!=name))
{
cout<<"could not find "<<name<<" in the list\n"; return;
}
if(head->next && head->name==name)
{
College *tmp=head;
head=head->next;
delete tmp;
tmp=NULL;
return;
}
College* tmp = head;
College* t;
while(tmp->next)
{
if(tmp->name==name)
{
College* tmp = head;
head = head->next;
delete tmp;
tmp->next=NULL;
}
if(tmp->next->name == name)
{
t = tmp->next;
tmp->next = tmp->next->next;
delete t;
return;
}
tmp=tmp->next;
}
cout<<"could not find "<<name<<" in the list\n";
};
/*Print the list of colleges int the college head*/
void printColleges(College *head)
{
cout<<"ALL Colleges in Database : \n";
College * temp = head;
while(temp!=NULL)
{
temp->Print();
temp=temp->next;
}
}
void AddDepartment(College *head)
{
if(!head)
{
cout<<"NO COLLEGES ADDED!!";
return;
}
string n,Dname;
int numS;
College* tmp = head;
College*tmp2 = tmp;
;
while(tmp)
{
cout<<"->"<<tmp->name;
tmp=tmp->next;
cout<<endl;
}
cout<<"Type a College name to Add a Department inside\n";
cin>>n;
cout<<"Enter Department name:";
cin>>Dname;
cout<<"Enter the number of students :";
cin>>numS;
while(n!=tmp->name)
{
tmp=tmp->next;
}
if(!tmp-> dep)
{
College * tmpD = new Department(Dname,numS);
Department*tmpDD = tmpD;
head=tmp;
return;
}
/*if(tmp->dep)
{
Department *tmp3 = tmp->dep->next;
t=tmp->dep;
dep->next=tmp3;
}*/
};
//void DeleteDepartment(College* head)
//{
//
//
// ;}
void PrintAll(College*head)
{
College * temp = head;
while(temp!=NULL)
{
temp->Print();
temp=temp->next;
}
};
int main(int argc, char** argv) {
int choice;
College*h = NULL;
while(choice!=11){
cout<<"\n\nMenu\n";
cout<<"1: Add a new college in the list  \n";
cout<<"2: Delete a college from the list \n";
cout<<"3: Add a department in a college\n";
cout<<"4: Delete a department from a college.\n";
cout<<"5: Print all the colleges along with their departments\n ";
cout<<"6: Delete all the departments of a particular college \n";
cout<<"7: Delete all the colleges from the list.\n";
cout<<"8: Print the total number of students in a college.\n";
cout<<"9: Find and print the college that has the highest number of students. \n";
cout<<"10: Find and print the department that has the highest number of students.\n";
cout<<"EXIT\n";
cin>>choice;
switch(choice)
{
case 1: AddCollege(*&h);
break;
case 2: DeleteCollege(*&h);
break;
case 3: printColleges(*&h);
break;
case 4:
AddDepartment(*&h);
break;
/* case 4:
DeleteDepartment(*&h);
break;
case 5:
PrintAll(*&h);
break;
case 6:
DeleteDepartment(*&h);
break;
case 7:
DeleteAllColleges(*&h);
break;
case 8:
NumOfStudentsInCollege(*&h);
break;
case 9:
HighestNumOfStudentsInCollege(*&h);
  break;
case 10:
HighestNumOfStudentsInDep(*&h);
break;
case 11:
cout<<"bye";
break;*/
default:
cout<<"\nInvalid menu choice";
}
}
}

Declare your Department class before it's called in College. (Move your Department declaration above your College declaration):
class Department
{
public:
string name;
int numOfStudents;
Department* next;
Department(){name[0] ; numOfStudents=0 ; next=NULL ;}
Department( string n , int numS){ name =" "; n ;numOfStudents = numS ; next=NULL;}
void Print(){cout<<name<<" "<<numOfStudents;}
};
class College{
public :
string name; //for name of the college
int numOfColleges;
int numDepartments; //number of departments in this college
Department * dep; //this will point to the department in this college
College * next; //the next pointer to point to the next college
College(){
name =" ";
numDepartments=0 ;
dep = NULL;
next=NULL;}
College (string n, int numD ){name=n ;next=NULL;}
void Print(){
cout<<name<<"\n";
}
};

Related

How to sort nodes from a stack and put into a queue

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

A string error and saving data (with linked list)

I'm working on this linked list project where I'm supposed to save the employee data in a linked list and apply some operations.
and I am new with c++ so I'll show you my code and please help me with it.
my questions are:
1- whenever I enter a full name the program keeps going in an infinite loop! i used getline() method and still its not working. but if I enterd just the first name it works fine.
2- I don't know how I can display or find the employee information if I used the methods I create it gives me random data.
my code:
main:
#include<iostream>
#include<string>
#include <fstream>
#include "EmployeeList.cpp"
using namespace std;
int main(){
string name;
int choice, id;
double Salary;
EmployeeList* employee = new EmployeeList();
cout<<"***********************************************"<<endl;
cout<<"**********EMPLOYEE MANAGEMENT SYSTEM***********"<<endl;
cout<<"***********************************************\n\n"<<endl;
do{
cout<<" 1--->Press 1 to INSERT EMPLOYMENT:"<<endl;
cout<<" 2--->Press 2 to FIND EMPLOYMENT INFO ID:"<<endl;
cout<<" 3--->Press 3 to DELETE EMPLOYMENT ID:"<<endl;
cout<<" 4--->Press 4 to SEARCH HIGHEST SALARY:"<<endl;
cout<<" 5--->Press 5 to DISPLAY ALL EMOLYMENTS:"<<endl;
cout<<" 6--->Press 6 to REVERSE DISPLAY ALL EMPLOYMENTS:"<<endl;
cout<<" 7--->Press 7 to EXIT:"<<endl;
cout<<"\n Enter Your Choice: ";
cin>>choice;
switch(choice){
case 1:
cout<<endl;
cout<<"Enter name : ";
getline(cin,name);
cout<<"Enter ID : ";
cin>>id;
cout<<"Enter Salary : ";
cin>>Salary;
cout<<endl;
employee ->INSERTEMPLOYMENT(name,id,Salary);
break;
case 2:
cout<<endl;
cout<<"Enter ID : ";
cin>>id;
cout<<endl;
employee->FINDEMPLOYMENTINFOID(id);
break;
case 3:
cout<<endl;
cout<<"Employee ID : ";
cin>>id;
cout<<endl;
employee-> DELETEEMPLOYMENTID(id);
break;
case 4:
cout<<endl;
employee->SEARCHHIGHESTSALARY();
break;
case 5:
cout<<endl;
employee->DISPLAYALLEMPLOYMENTS();
break;
case 6:
cout<<endl;
employee->REVERSEDISPLAYALLEMPLOYMENTS(employee->getHead());
break;
case 7:
exit(0);
default:
cout<<"Invalid choice."<<endl;
break;
}
} while (true);
return 0;
}
Employee:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Employee{
private:
string name;
int ID;
double Salary;
Employee* next;
public:
//Constructor
Employee (string n, int id, double s){
n = name;
id = ID;
s = Salary;
this->next = NULL;
}
//Setters
void setName(string n){
n = name;
}
void setID(int id){
id = ID;
}
void setSalary(double s){
s = Salary;
}
void setNext(Employee* next){
this->next = next;
}
//Getters
string getName(){
return name;
}
int getID(){
return ID;
}
double getSalary(){
return Salary;
}
Employee* getNext(){
return this->next;
}
};
EmployeeList:
#include "Employee.cpp"
using namespace std;
class EmployeeList{
private:
Employee* head;
public:
//Constructor
EmployeeList(){
head = NULL;
}
//getter
Employee* getHead(){
return head;
}
//insert method
void INSERTEMPLOYMENT (string name, int id, double Salary){
Employee* newnode = new Employee(name, id, Salary);
if(head == NULL){
head = newnode;
}
else {
Employee* temp = head;
while(temp->getNext() != NULL){
temp = temp->getNext();
}
temp->setNext(newnode);
}
cout<<"The employee record was added successfully."<<endl;
cout<<"------------------------------------------"<<endl;
}
//info
void FINDEMPLOYMENTINFOID (int id){
Employee *temp = head;
bool status = false;
while(temp != NULL){
if(temp->getID() == id){
status = true;
cout<<"Employee Name = "<<temp->getName()<<endl;
cout<<"Employee ID = "<<temp->getID()<<endl;
cout<<"Employee Salary = "<<temp->getSalary()<<endl;
cout<<"---------------------------------------"<<endl;
}
temp = temp->getNext();
}
if(status == false) {
cout<<"Employee is not found in the list."<<endl;
cout<<"--------------------------------------------"<<endl;
}
}
//display
void DISPLAYALLEMPLOYMENTS (){
Employee* temp = head;
while(temp != NULL){
cout<<"Employee Name = "<<temp->getName()<<endl;
cout<<"Employee ID = "<<temp->getID()<<endl;
cout<<"Employee Salary = "<<temp->getSalary()<<endl;
cout<<"---------------------------------------"<<endl;
temp = temp->getNext();
}
}
};
There are 2 major problems here.
Assignment are not reversible...
In Employee class most assignment are reversed. The constructor is:
//Constructor
Employee (string n, int id, double s){
n = name; // replace the local copy of n with name!!!
id = ID;
s = Salary;
this->next = NULL;
}
It should of course be:
//Constructor
Employee(string n, int id, double s) {
name = n;
ID = id;
Salary= s;
this->next = NULL;
}
This is the reason why your Employee instances only contain garbage values...
Mixing getline and stream extractor is dangerous
When you use a stream extractor to read an integer value, the stream pointer is positioned immediately after the last number, so just before the end of line. If you use getline immediately after that, you will read that newline character only and will get an empty string. A simple trick is to consistently skip over empty lines:
case 1:
cout << endl;
cout << "Enter name : ";
for (;;) {
getline(cin, name);
if (name != "") break;
}
...
That should be enough to fix the immediate problems. But others are still around:
you never test the state of the input streams: if the users types an incorrect number you will not detect it and your program will have a wrong behaviour
EmployeeList being a linked list should behave as a container: it should automatically destroys its elements in its destructor. And because of that and of the rule of 5, it should also have a custom (or deleted) copy constructor and copy assignment operator.
constructor have a special syntax to directly initialize their members instead of first default initialize them and then assign to them. Not only it is slightly more efficient, but it is the only way to initialize const members. For that reason the idiomatic way should be:
//Constructor
Employee (string n, int id, double s)
: name(n), ID(id), Salary(s), next(nullptr) {}

'temp' is undeclared, first use this function

#include<iostream>
#include<conio.h>
#include<string>
#include<cstring>
#include<stdlib.h>
using namespace std;
bool rgstr_stdnt(struct student *stud,struct list *ls);
double calculate_aggregate(struct student *);
void srch_student(struct student * next);
void addToList(struct student *stud, struct list *l);
void display(struct student *stud, struct list *l);
struct student
{
char name[20];
int matric_marks, inter_marks, aptitude_marks;
int temp;
student *next;
};
struct list
{
char name[20];
double aggr;
list *next;
};
this is where the problem shows up, it says temp undeclared, first use this function and I'm not able to rectify it
void srch_stdnt(struct student *stud)
{
char name[60];
cout << "Enter Student to search :";
cin>>name;
cout << name;
//down here, the error comes and whatever i knew, i have tried to solve it but could not
while (temp!=NULL){
if(strcmp(temp->name, name)==0){
}
temp = temp->next;
}
cout << "No match found";
}
int main()
{
student * temp=new student();
student *s;
s = (struct student *) malloc(sizeof(struct student));
struct list *ls;
ls = (struct list *) malloc(sizeof(struct list));
strcpy(ls->name,"");
ls->aggr = 0;
ls->next= NULL;
do
{
cout<<" STUDENT ENROLLMENT AND RECORDS MANAGEMENT"<<endl;
cout<<"1- To Enroll A New Sudent."<<endl;
cout<<"2- To View The Enrolled Students."<<endl;
cout<<"3- To Search Through The Already Enrolled Students."<<endl;
cout<<"4- Exit."<<endl;
int input;
cin>>input;
if (input == 1)
{
rgstr_stdnt(s, ls);
}
else if (input == 2)
{
display(s, ls);
}
else if(input == 3)
{
void srch_student(struct student * stud);
}
else if (input == 4)
exit(0);
cout<<endl;
} while(1);
getch();
}
bool rgstr_stdnt(struct student *stud,struct list *ls)
{
student *s = stud;
cout<<"Enter Name Of The Student: "<<endl;
cin>>s->name;
cout<<"Enter Percentage in 10th Grade: "<<endl;
cin>>s->matric_marks;
cout<<"Enter Intermediate Percentage:"<<endl;
cin>>s->inter_marks;
cout<<"Enter Percentage In Aptitude Test: "<<endl;
cin>>s->aptitude_marks;
double aggregate;
aggregate = calculate_aggregate(s);
cout<<"Aggregate Percentage Is: "<< aggregate<<"%"<<endl;
if (aggregate >= 70)
{
cout<<"-> Student Enrolled In BSCS. <-"<<endl;
addToList(s,ls);
return true;
}
else if (aggregate >= 60)
{
cout<<"-> Student Enrolled In BE. <-"<<endl;
addToList(s,ls);
return true;
}
else if (aggregate >=50)
{
cout<<"-> Student Enrolled In MS. <-"<<endl;
addToList(s,ls);
return true;
}
else
{
cout<<"Sorry, Low Percentage. Student Can't Be Enrolled!"<<endl;
return false;
}
}
double calculate_aggregate(struct student *stud)
{
student *s = stud;
double aggr;
aggr = s->matric_marks * 10/100 + s->inter_marks * 50/100 +
s->aptitude_marks * 40/100;
return aggr;
}
void addToList(struct student *stud, struct list *l)
{
list *pointer = l;
while (pointer->next != NULL)
{
pointer = pointer->next;
}
pointer->next = (struct list *) malloc(sizeof(struct list));
pointer = pointer->next;
strcpy(pointer->name , stud->name);
pointer->aggr = calculate_aggregate(stud);
pointer->next = NULL;
}
void display(struct student *stud, struct list *l)
{
list *pointer = l;
if (pointer->next == NULL)
cout<<"No Students Enrolled Yet."<<endl;
else
{
cout<<" !- - - - - - - - -. STUDENTS RECORDS .- - - - - - - - - -! "
<<endl;
while (pointer->next != NULL)
{
pointer = pointer->next;
cout<<"Name Of Student: "<<pointer->name<<endl;
cout<<"Aggregate Is: "<<pointer->aggr<<endl;
if (pointer->aggr >= 70)
cout<<"-> Student Enrolled In BSCS. <-"<<endl;
else if(pointer->aggr >=60)
cout<<"-> Student Enrolled In BE. <-"<<endl;
else
cout<<"-> Student Enrolled In MS. <-"<<endl;
cout<<endl;
}
}
}
Any who could help me solve this, i'd really be grateful.
As the error message states, you're using a variable called temp that you haven't declared yet. You need to declare it and give it an initial value:
struct student *temp = stud;
while (temp!=NULL){
...
//down here, the error comes and whatever i knew, i have tried to solve it but could not
while (temp!=NULL){
You have not declared temp in the function. That explains the compiler error.
Perhaps you meant to use:
struct student* temp = stud;
while ( temp != NULL )
Since you are in C++ land, discard the struct and use:
student* temp = stud;
while ( temp != NULL )
That change change can be made in rest of your code too.

Segmentation Fault in deleting a node

I have a C++ Code that just manipulates basic linked list - add a new node, delete a node and view the list
//UNIX Environment
#include <iostream>
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#define clear() printf("\033[H\033[J")
using namespace std;
struct node
{
int val;
node *next;
};
struct node* head = NULL;
void add_node(struct node *hea)
{
char f;
int val;
cout<<"Enter value : ";
cin>>val;
if(head==NULL)
{
head = new(struct node);
head->val = val;
head->next = NULL;
}
else
{
node *traverser = hea;
node *traverser_prev = NULL;
while(traverser!=NULL)
{
traverser_prev = traverser;
traverser=traverser->next;
}
traverser = new(struct node);
traverser->val = val;
traverser->next = NULL;
traverser_prev->next=traverser;
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}
void view_list(struct node *hea)
{
char f;
node *traverser = hea;
while(traverser!=NULL)
{
cout<<traverser->val<<" ";
traverser=traverser->next;
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}
void delete_node(node *hea)
{
char f;
int del_value;
cout<<"Enter value to be deleted :";
cin>>del_value;
node *traverser = hea;
cout<<"OK1\n";
node* traverser_prev = NULL;
cout<<"OK2\n";
while(traverser!=NULL)
{
if(traverser->val==del_value)
{
if(traverser==hea)
{
hea=traverser->next;
cout<<"Here cond1\n";
delete traverser;
}
else
{
traverser_prev->next = traverser->next;
cout<<"Here cond2\n";
}
}
else
{
traverser_prev = traverser;
traverser = traverser->next;
cout<<"Here cond3\n";
}
}
cout<<"\nEnter Y to return : ";
cin>>f;
while(f!='Y')
{
cout<<"Wrong entry.Enter again : ";
cin>>f;
}
return;
}
int main(int argc, char* argv[])
{
while(1)
{
clear();
int choice;
cout<<"POINTER BASICS\n";
cout<<"1. Add new element\n";
cout<<"2. View elements\n";
cout<<"3. Delete element\n";
cout<<"4. Exit\n";
cout<<"Enter choice: ";
cin>>choice;
switch(choice)
{
case 1: add_node(head);
break;
case 2: view_list(head);
break;
case 3: delete_node(head);
break;
default:break;
}
if(choice==4)
break;
}
}
However, whenever I try to delete node, it throws me a segmentation fault error with core dumped. What is the reason for the error?
One problem is that in the delete_node function you pass the list head by value, which means that the pointer is copied and inside the function you only modify the copy.
There are two solutions: Either don't use the argument at all and only use the global variable, or pass the argument by reference:
void delete_node(node*& hea)
Is it possible that when you are executing the line
traverser_prev->next = traverser->next;
traverser_prev == NULL?

How To Modify Data In a c++ Linked List

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.