Updating a node in linked list - c++

I want to update a data in the node of the linked list. I have tried to but it does not changed the data within. If anyone can help me with this, i would be really appreciated.
This is my Main Driver Code
#include <iostream>
#include <fstream>
#include <string>
#include "item.h"
using namespace std;
LinkedList list;
Item item;
Node* node;
void menu()
{
here:
int choice = 0;
string itemId, title, type, loan, num_copy, fee, genre;
cout << "Welcome to Genie\'s video store" << endl;
cout << "Enter an option below" << endl;
cout << "1. Add a new item" << endl;
cout << "2. Delete an item" << endl;
cout << "3. Update an item" << endl;
cout << "4. Search an item by ID" << endl;
cout << "5. Search an item by title" << endl;
cout << "6. Display all item" << endl;
cout << "Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == 1)
{
system("cls");
list.addItem(list);
cout << endl;
goto here;
}
else if (choice == 2)
{
system("cls");
list.deleteItem(list);
cout << endl;
goto here;
}
else if (choice == 3)
{
system("cls");
list.updateItem(list);
cout << endl;
goto here;
}
else if (choice == 4)
{
system("cls");
list.searchById(list);
cout << endl;
goto here;
}
else if (choice == 5)
{
system("cls");
list.searchByTitle(list);
cout << endl;
goto here;
}
else if (choice == 6)
{
system("cls");
list.printAll(list);
cout << endl;
goto here;
}
}
int main(int argc, char* argv[])
{
ifstream file("items.txt", ios::in);
if (!file)
{
cerr << "Error in opening file.";
throw(file);
}
list.readAllFile(file, list);
file.close();
menu();
return 0;
}
And this is my item.h:
#pragma once
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Item
{
protected:
string itemId, title, type, loan, num_copy, fee, genre;
public:
Item() {}
Item(string itemId, string title, string type, string loan, string num_copy, string fee, string genre)
: itemId(itemId), title(title), type(type), loan(loan), num_copy(num_copy), fee(fee), genre(genre)
{}
~Item() {}
string& getItemId() { return this->itemId; }
string& getTitle() { return this->title; }
string& getType() { return this->type; }
string& getLoan() { return this->loan; }
string& getCopy() { return this->num_copy; }
string& getFee() { return this->fee; }
string& getGenre() { return this->genre; }
void setItemId(string itemId) { this->itemId = itemId; }
void setTitle(string title) { this->title = title; }
void setFee(string fee) { this->fee = fee; }
void setCopy(string num_copy) { this->num_copy = num_copy; }
void setLoan(string loan) { this->loan = loan; }
void setType(string type) { this->type = type; }
void setGenre(string genre) { this->genre = genre; }
};
class Node
{
private:
Item data;
Node* next;
public:
Node() {}
Node(Item newData)
{
data = newData;
next = nullptr;
}
Node(Item newData, Node* nextNode)
{
data = newData;
next = nextNode;
}
~Node() {}
Node* getNext() { return next; }
void setNext(Node* newNext) { next = newNext; }
Item getData() { return data; }
Item setData(Item newData) { data = newData; }
Node* createNode(Item newData);
};
class LinkedList
{
private:
Node* head;
Node* tail;
public:
LinkedList() : head(NULL), tail(NULL)
{}
~LinkedList() {}
void createList(LinkedList& list);
void insertHead(LinkedList& list, Node* temp);
void appenTail(LinkedList& list, Node* temp);
void readLine(ifstream& file, Item& item);
void readAllFile(ifstream& file, LinkedList& list);
void printOneLine(Item item);
void printAll(LinkedList list);
//void writeToFile(LinkedList& list);
void addItem(LinkedList& list);
void deleteItem(LinkedList list);
void updateItem(LinkedList& list);
void searchById(LinkedList list);
void searchByTitle(LinkedList list);
};
Finally, this is my item.cpp file:
void LinkedList::updateItem(LinkedList& list)
{
string updateId, updateTitle, updateType, updateLoan, updateNumCopy, updateFee, updateGenre;
Node node;
Node* temp = list.head;
bool found = false;
if (temp == nullptr)
{
cerr << "There are no items." << endl;
exit(EXIT_FAILURE);
}
cout << "Enter the item's id and other info you want to update below:" << endl;
cout << "ID: ";
cin.ignore();
getline(cin, updateId);
cout << "Title: ";
cin.ignore();
getline(cin, updateTitle);
cout << "Type: ";
cin.ignore();
getline(cin, updateType);
cout << "Loan type: ";
cin.ignore();
getline(cin, updateLoan);
cout << "Copy(s): ";
cin.ignore();
getline(cin, updateNumCopy);
cout << "Rental fee: ";
cin.ignore();
getline(cin, updateFee);
cout << "Rental genre: ";
cin.ignore();
getline(cin, updateGenre);
while (temp != nullptr)
{
Item item = temp->getData();
if ((_stricmp(item.getItemId().c_str(), updateId.c_str()) == 0) || (_stricmp(item.getTitle().c_str(), updateTitle.c_str()) == 0))
{
item.getItemId() = updateId;
item.getTitle() = updateTitle;
item.getType() = updateType;
item.getLoan() = updateLoan;
item.getFee() = updateFee;
item.getGenre() = updateGenre;
found = true;
}
temp = temp->getNext();
}
if (!found)
{
cerr << "Item not found." << endl;
exit(EXIT_FAILURE);
}
}
So the main problem is that inside the updateItem() function, we do not know how to make the function to update a specific variables of the object. I have tried the above updateItem function and the final result is that none of the item's information is changed.
Thank you.

Item item = temp->getData();
getData returns a copy and it is stored inside a new variable. You are making changes but it is not in the right variable. One solution would be to store and return a reference:
// return a reference
Item & getData() { return data; }
// store a reference
Item & item = temp->getData();

Related

How can I implement a linked list and allow users to choose a specific node to remove with C++?

I've spent pretty much all day trying to do this, I understand pointers and what a linked list does, but I don't know how to actually code it and all I've found are Java and C examples which don't help because I'm using C++.
Thanks in advance for taking a look at my code and helping me, I really appreciate it considering how many days I've spent stressed out and confused about this. I'm not going to lie so far most of my deleteNode function is probably trash. But like I've said I'm just lost I don't even know where to start or how to progress because I only understand the concepts.
This is my data file.
John Doe 80
Jane Smith 70
Bill Jones 50
Pat Hughes 90
Sam Sosa 40
This is my Header file
#include<string>
using namespace std;
class student {
public:
student(); // constructor method
void st_fn(string fn);
string st_fn();
void st_ln(string ln);
string st_ln();
void st_score(float s);
float st_score();
string st_pass_or_fail();
// need a pointer to the next object
student *nxt_ptr;
protected: // protected can be inherited
float m_score;
string m_ln;
string m_fn;
string m_pf_msg;
};
student::student() //constructor
{
nxt_ptr = NULL;
m_score = 0;
}
void student::st_fn(string fn)
{
m_fn = fn;
}
string student::st_fn()
{
return m_fn;
}
void student::st_ln(string ln)
{
m_ln = ln;
}
string student::st_ln()
{
return m_ln;
}
void student::st_score(float s)
{
m_score = s;
}
float student::st_score()
{
return m_score;
}
string student::st_pass_or_fail()
{
if (m_score >= 60)
m_pf_msg = "PASSED";
else
m_pf_msg = "FAILED";
return m_pf_msg;
}
This is my .cpp file.
#include<iostream>
#include<string>
#include<fstream>
#include "Header.h"
using namespace std;
int display_menu()
{
int option;
cout << endl << endl;
cout << "1. Display List" << endl;
cout << "2. Add a student" << endl;
cout << "3. Delete first student" << endl;
cout << "4. Search by Last Name" << endl;
cout << "5. Exit" << endl;
cin >> option;
return option;
}
student * search_last_name(student *h)
{
student *f = NULL;
student *t = NULL;
string s_ln;
// prompt for last name to search for
cout << "Enter Last Name of the Student";
cin >> s_ln;
if (h != NULL)
{
t = h;
while (t != NULL)
{
if (t->st_ln() == s_ln)
f = t; // found the last name so save t
t = t->nxt_ptr;
}
}
else
cout << "List is empty" << endl;
return f;
}
void add_student(student *&head) // h is the head of the list
{
student *new_st, *r;
string fn, ln;
float s;
cout << "Enter new students first name, last name and score";
cin >> fn >> ln >> s;
// instantiate a new node, use new_st
new_st = new student;
new_st->st_fn(fn);
new_st->st_ln(ln);
new_st->st_score(s);
if (head == NULL)
head = new_st;
else
{
// find the last node, use r for this
// write code
r = head;
while (r->nxt_ptr != nullptr)
r = r->nxt_ptr;
// add to the back of the list
// write code
r->nxt_ptr = new_st;
} // end of else
} // end of add student
student * delete_front(student * head)
{
student *t;
// delete front node
// check for empty list
if (head != NULL)
{
// delete first node
t = head;
head = head->nxt_ptr;
delete(t);
}
else
cout << "List is empty - nothing to delete" << endl;
return head;
}
void deleteNode(struct Node *head, struct Node *n)
{
// When node to be deleted is head node
if (head == n)
{
n = head->next;
//Remove the link of next node
head->next = head->next->next;
return;
}
//When not first node, folow the normal deletion process
//Find the previous node
struct Node *prev = head;
while (prev->next != NULL && prev->next != n)
prev = prev->next;
// Check if node really exists in Linked List
if (prev->next == NULL)
{
cout << endl << "Given node is not present in Linked List";
return;
}
//Remove node from linked list should it exist
prev->next = prev->next->next;
return;
}
void display_list(student *t)
{
if (t == NULL)
cout << "List is Empty!";
else
{
while (t != NULL)
{
cout << "******Student******" << endl;
cout << t->st_ln() << endl;
cout << t->st_fn() << endl;
cout << t->st_score() << endl << endl;
t = t->nxt_ptr;
}
}
}
int main()
{
string ln, fn;
float s;
int n;
ifstream infile;
student *head = NULL; //pointer to a student object
student *cp = NULL; // pointer to end of the list
student *new_st = NULL; // pointer to a new student object
student *f = NULL; // pointer to found node
int option; // the numbe of menu item the user selects
infile.open("lab8d.txt");
while (!infile.eof())
{
infile >> fn >> ln >> s;
//instantiate a student object
new_st = new student;
//load the object with data
new_st->st_fn(fn);
new_st->st_ln(ln);
new_st->st_score(s);
// check for empty list - its a special case
if (head == NULL)
{
head = new_st;
cp = new_st;
}
else // list is not empty
{
cp->nxt_ptr = new_st;
cp = new_st;
}
} // end of loop
// loop to give the user some options
option = display_menu();
while (option != 5)
{
if (option == 1)
display_list(head);
else if (option == 2)
add_student(head);
else if (option == 3)
head = delete_front(head);
else if (option == 4)
{
f = search_last_name(head);
if (f != NULL)
{
cout << f->st_fn() << endl;
cout << f->st_ln() << endl;
cout << f->st_score() << endl;
cout << f->st_pass_or_fail() << endl;
}
else
cout << "Name not in the list" << endl;
}
else if (option == 6)
{
cout << "Enter the number of the node you would like to delete: " << endl;
cin >> n;
}
option = display_menu();
}
system("pause");
return 0;
}
The simpler and self-contained your functions are, the easier they are to test and debug, and the less like they are to fail.
Try something more like this:
Student.h:
#include <string>
class student_list;
class student
{
public:
student();
student(const std::string &fn, const std::string &ln, float s, student *nxt = NULL);
void next(student *s);
student* next() const;
void firstName(const std::string &fn);
std::string firstName() const;
void lastName(const std::string &ln);
std::string lastName() const;
void score(float s);
float score() const;
std::string pass_or_fail() const;
void display(bool showPassOrFail = false) const;
friend class student_list;
protected: // protected can be inherited
student *m_next;
std::string m_fn;
std::string m_ln;
float m_score;
};
Student.cpp:
#include "Student.h"
#include <iostream>
student::student()
: m_next(NULL), m_score(0)
{
}
student::student(const std::string &fn, const std::string &ln, float s, student *nxt)
: m_next(nxt), m_fn(fn), m_ln(ln), m_score(s)
{
}
void student::next(student *s)
{
m_next = s;
}
student* student::next() const
{
return m_next;
}
void student::firstName(const std::string &fn)
{
m_fn = fn;
}
std::string student::firstName() const
{
return m_fn;
}
void student::lastName(const std::string &ln)
{
m_ln = ln;
}
std::string student::lastName() const
{
return m_ln;
}
void student::score(float s)
{
m_score = s;
}
float student::score() const
{
return m_score;
}
std::string student::pass_or_fail() const
{
if (m_score >= 60)
return "PASSED";
else
return "FAILED";
}
void student::display(bool showPassOrFail) const
{
std::cout << lastName() << std::endl;
std::cout << firstName() << std::endl;
std::cout << score() << std::endl;
if (showPassOrFail)
std::cout << pass_or_fail() << std::endl;
}
StudentList.h:
#include <string>
class student;
class student_list
{
public:
student_list();
~student_list();
student* search_last_name(const std::string &ln);
student* insert(const std::string &fn, const std::string &ln, float s, student* after = NULL);
bool remove(int idx);
void display() const;
private:
student *m_head;
};
StudentList.cpp:
student_list::student_list()
: m_head(NULL)
{
}
student_list::~student_list()
{
while (m_head)
remove(0);
}
student* student_list::search_last_name(const std::string &ln)
{
student *t = m_head;
while (t)
{
if (t->lastName() == ln)
break; // found the last name
t = t->next();
}
return t;
}
student* student_list::insert(const std::string &fn, const std::string &ln, float s, student* after)
{
student **r;
if (after)
{
// add to list after the specified node
// get pointer to next node
r = &(after->m_next);
}
else
{
// add to the back of the list
// find pointer to last node
r = &m_head;
while (*r)
r = &((*r)->m_next);
}
// instantiate a new node
student *new_st = new student(fn, ln, s);
if (after)
new_st->next(*r);
// add to list
*r = new_st;
return new_st;
}
bool student_list::remove(int idx)
{
// delete a node at index
// find pointer to node
student **r = &m_head;
while ((*r) && (idx-- > 0))
r = &((*r)->m_next);
if (*r)
{
// delete node
student *t = *r;
*r = t->next();
delete t;
return true;
}
return false;
}
void student_list::display() const
{
student *t = m_head;
if (!t)
std::cout << "List is Empty!" << std::endl;
else
{
do
{
std::cout << "******Student******" << std::endl;
t->display();
t = t->next();
}
while (t);
}
}
Main.cpp:
#include "Student.h"
#include "StudentList.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <limits>
#include <cstdlib>
int read_number()
{
int value;
while (!(std::cin >> value))
{
std::cout << "Must be a number, try again: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return value;
}
int display_menu()
{
int option;
std::cout << std::endl << std::endl;
std::cout << "1. Display List" << std::endl;
std::cout << "2. Add a student" << std::endl;
std::cout << "3. Delete first student" << std::endl;
std::cout << "4. Search by Last Name" << std::endl;
std::cout << "5. Delete student by index" << std::endl;
std::cout << "6. Exit" << std::endl << std::endl;
std::cout << "Choice: ";
do
{
option = read_number();
if ((option >= 1) && (option <= 6))
break;
std::cout << "Must be 1..6, try again: ";
}
while (true);
return (option != 6) ? option : -1;
}
int main()
{
student_list students;
std::ifstream infile("lab8d.txt");
if (infile.is_open())
{
student *cp = NULL;
std::string ln, fn;
float s;
while (infile >> fn >> ln >> s)
cp = students.insert(fn, ln, s, cp);
infile.close();
}
// loop to give the user some options
int option; // the number of menu item the user selects
while ((option = display_menu()) != -1)
{
switch (option)
{
case 1:
{
students.display();
break;
}
case 2:
{
// prompt for student info
std::string info;
std::cout << "Enter new student's first name, last name, and score: ";
std::string ln, fn;
float s;
if (std::cin >> fn >> ln >> s)
students.insert(fn, ln, s);
break;
}
case 3:
{
if (!students.remove(0))
std::cout << "List is empty" << std::endl;
break;
}
case 4:
{
// prompt for last name to search for
std::string ln;
std::cout << "Enter Last Name of the Student: ";
if (std::cin >> ln)
{
student *f = students.search_last_name(ln);
if (f)
f->display(true);
else
std::cout << "Name not found in List" << std::endl;
}
break;
}
case 5:
{
std::cout << "Enter the index of the Student to Delete: " << std::endl;
int idx = read_number();
if (!students.remove(idx))
std::cout << "Index not found in List" << std::endl;
break;
}
}
}
std::system("pause");
return 0;
}
That being said, you really should be using the std::list container instead, eg:
Student.h:
#include <string>
class student_list;
class student
{
public:
student();
student(const std::string &fn, const std::string &ln, float s);
void firstName(const std::string &fn);
std::string firstName() const;
void lastName(const std::string &ln);
std::string lastName() const;
void score(float s);
float score() const;
std::string pass_or_fail() const;
void display(bool showPassOrFail = false) const;
friend class student_list;
protected: // protected can be inherited
std::string m_fn;
std::string m_ln;
float m_score;
};
Student.cpp:
#include "Student.h"
#include <iostream>
student::student()
: m_score(0)
{
}
student::student(const std::string &fn, const std::string &ln, float s)
: m_fn(fn), m_ln(ln), m_score(s)
{
}
void student::firstName(const std::string &fn)
{
m_fn = fn;
}
std::string student::firstName() const
{
return m_fn;
}
void student::lastName(const std::string &ln)
{
m_ln = ln;
}
std::string student::lastName() const
{
return m_ln;
}
void student::score(float s)
{
m_score = s;
}
float student::score() const
{
return m_score;
}
std::string student::pass_or_fail() const
{
if (m_score >= 60)
return "PASSED";
else
return "FAILED";
}
void student::display(bool showPassOrFail) const
{
std::cout << lastName() << std::endl;
std::cout << firstName() << std::endl;
std::cout << score() << std::endl;
if (showPassOrFail)
std::cout << pass_or_fail() << std::endl;
}
Main.cpp:
#include "Student.h"
#include <list>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <limits>
#include <algorithm>
#include <cstdlib>
int read_number()
{
int value;
while (!(std::cin >> value))
{
std::cout << "Must be a number, try again: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return value;
}
int display_menu()
{
int option;
std::cout << std::endl << std::endl;
std::cout << "1. Display List" << std::endl;
std::cout << "2. Add a student" << std::endl;
std::cout << "3. Delete first student" << std::endl;
std::cout << "4. Search by Last Name" << std::endl;
std::cout << "5. Delete student by index" << std::endl;
std::cout << "6. Exit" << std::endl << std::endl;
std::cout << "Choice: ";
do
{
option = read_number();
if ((option >= 1) && (option <= 6))
break;
std::cout << "Must be 1..6, try again: ";
}
while (true);
return (option != 6) ? option : -1;
}
int main()
{
std::list<student> students;
std::ifstream infile("lab8d.txt");
if (infile.is_open())
{
std::string ln, fn;
float s;
while (infile >> fn >> ln >> s)
students.push_back(student(fn, ln, s));
infile.close();
}
// loop to give the user some options
int option; // the number of menu item the user selects
while ((option = display_menu()) != -1)
{
switch (option)
{
case 1:
{
if (students.empty())
std::cout << "List is Empty!" << std::endl;
else
{
for(const auto &s : students)
{
std::cout << "******Student******" << std::endl;
s.display();
}
}
break;
}
case 2:
{
// prompt for student info
std::string info;
std::cout << "Enter new student's first name, last name, and score: ";
std::string ln, fn;
float s;
if (std::cin >> fn >> ln >> s)
students.push_back(student(fn, ln, s));
break;
}
case 3:
{
if (students.empty())
std::cout << "List is empty" << std::endl;
else
students.erase(students.begin());
break;
}
case 4:
{
// prompt for last name to search for
std::string ln;
std::cout << "Enter Last Name of the Student: ";
if (std::cin >> ln)
{
auto f = std::find(students.begin(), students.end(),
[&](const student &s){ return (s.lastName() == ln); }
);
if (f != students.end())
f->display(true);
else
std::cout << "Name not found in List" << std::endl;
}
break;
}
case 5:
{
std::cout << "Enter the index of the Student to Delete: " << std::endl;
int idx = read_number();
if ((idx < 0) || (idx >= students.size()))
std::cout << "Index not found in List" << std::endl;
else
students.erase(std::next(students.begin(), idx));
break;
}
}
}
std::system("pause");
return 0;
}

Undefined reference to another class?

I'm using a class within a class and I'm getting errors, I think it's a linking problem. I get "undefined reference to 'Node::setlink()', 'Node::getlink()', and etc. It's all the node functions I used in linked_list.cpp that are the problem.
For example, linked_list.cpp:(.text+0x9de): undefined reference to
`Node::getlink()'
Linked_list.cpp
#include "linked_list.hpp"
#include "node.hpp"
#include <iomanip>
#include <iostream>
using namespace std;
//default constructor
Linked_list::Linked_list(void)
{
head = new Node();
tail = new Node();
head->setlink(NULL);
tail->setlink(NULL);
cnt = 0;
}
//constructor
Linked_list::Linked_list(data x)
{
head = new Node();
tail = new Node();
Node *newnode = new Node(x);
head->setlink(newnode);
newnode->setlink(tail);
cnt++;
}
//class function
void Linked_list::insert_node(data x)
{
Node *newNode = new Node(x);
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
newNode->setlink(tail);
head->setlink(newNode);
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while(curr->getlink() != NULL || newNode->getupc() <= curr->getupc())
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
prev->setlink(newNode);
newNode->setlink(curr);
}
cnt++;
}
//Class function
void Linked_list::delete_node(int u)
{
char choice;
data temp;
Node *newNode = new Node();
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
delete newNode;
delete prev;
delete curr;
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while (curr->getlink() != NULL || curr->getupc() != u )
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
prev->setlink(curr->getlink());
cout << "Are you sure you want to delete?\n";
cin >> choice;
if (choice == 'y' || choice == 'Y')
{
delete curr;
cnt--;
}
else
{
choice = 'n';
}
}
}
//Class function
void Linked_list::traverse()
{
data temp;
Node *curr = new Node();
if (head == NULL)
{
delete curr;
cout << "The list is empty!\n";
}
else
{
curr->setlink(head->getlink());
while(curr->getlink() != NULL)
{
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
}
void Linked_list::retrieve_node(int u)
{
data temp;
Node *x;
x = new Node();
if (head == NULL)
{
delete x;
}
else if (head != NULL)
{
x->setlink(head->getlink());
while (x->getlink() != NULL || x->getupc() != u)
{
x->setlink(x->getlink());
}
temp = x->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
void Linked_list::check_empty()
{
if (head != NULL)
{
cout << "The list is empty.\n";
}
else
{
cout << "The list is not empty.\n";
}
}
linked_list.hpp
#include "node.hpp"
#ifndef linked_list_hpp
#define linked_list_hpp
class Linked_list
{
Node *head;
Node *tail;
int cnt;
public:
//default constructor creates empty linked list
Linked_list(void);
//Constructor that creates first node with values
Linked_list(data x);
//Inserts node at correct spot
void insert_node(data x);
//deletes specific node
void delete_node(int u);
//goes through whole list and prints out
void traverse(void);
//returns specific node
void retrieve_node(int u);
//checks if list is empty
void check_empty();
return_number();
};
#endif
node.hpp
#ifndef node_hpp
#define node_hpp
#include "node.hpp"
#include <string>
using namespace std;
struct data
{
int UPC;
string desc;
int quantity;
double cost;
int aisle;
};
class Node
{
data item;
Node *link;
public:
Node(void);
Node(data x);
void setlink(Node *ptr);
Node* getlink();
int getupc();
data get_structure();
bool compare_item(string i);
double processdata();
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
link = NULL;
}
Node::Node(data x)
{
item = x;
}
void Node::setlink(Node *ptr)
{
link = ptr;
}
Node* Node::getlink()
{
return link;
}
int Node::getupc()
{
return item.UPC;
}
data Node::get_structure()
{
return item;
}
bool Node::compare_item(string i)
{
if(i==item.desc)
{
return true;
}
else
{
return false;
}
}
double Node::processdata()
{
return item.cost*item.quantity;
}
main function
#include <iostream>
#include "node.cpp"
#include "linked_list.cpp"
using namespace std;
void fromfile(Linked_list &x);
void tofile(Linked_list &x);
int main(void)
{
Linked_list ll;
int x, y;
data a;
do
{
cout << "1.Add a grocery item\n" ;
cout << "2.Delete an item\n";
cout << "3.Retrieve an item\n";
cout << "4.Traverse the list forwards and print out all of the items\n";
cout << "5. Exit the program.\n";
cin >> x;
switch(x)
{
case 1:
cout << "Enter UPC code\n";
cin >> a.UPC;
cout << "Enter description(name of item)\n";
cin >> a.desc;
cout << "Enter quantity\n";
cin >> a.quantity;
cout << "Enter cost\n";
cin >> a.cost;
cout << "Enter aisle\n";
cin >>a.aisle;
ll.insert_node(a);
case 2:
cout << "Enter UPC of item you'd like to delete.\n";
cin >> y;
ll.delete_node(y);
case 3:
cout << "Enter UPC code.\n";
cin >> y;
ll.retrieve_node(y);
case 4:
ll.traverse();
case 5:
cout << "Bye!\n";
default:
cout << "Wrong choice, try again!\n";
}
}while (x != 5);
return 0;
}
Please help me out, this is due in 2 hours. I think I got it running somehow for a while and after the code performs in main, it just stop creating output after it reaches a linked_list function. Then, I can't enter anything afterwards.
The only thing not compiling is the linked_list.cpp, and I get a winmain error as well.

Read Access Violation Code: 0xCDCDCDE1 and Code :0xCDCDCDE1

I'm doing a Shopping Mall project in Link List C++. In which I have to insert new Shop,Search Shop, Delete Shop, Count Shops and Display all. I written some of code.
I wrote the code but:
(1) it give error in input after when I input 2nd time and press input at last input i gives following Exception.
"Exception thrown: read access violation.
std::_String_alloc > >::_Mysize(...) returned 0xCDCDCDE1."
(2) When I display it give following Exception:
Exception thrown: read access violation.
temp was 0xCDCDCDCD.
Here is main.
int main()
{
ShoppingMallList* shopList=new ShoppingMallList();
string name="";
int shopNumber;
string brandShop;
int floor;
string shoptype;
do
{
system("cls");
cout << "**************WELCOME TO MALL**************\n1: Add Shop\n2: Search Shop\n3: Count Shops\n4:Display Shops\n5: Quit" << endl;
int option;
cin >> option;
switch (option)
{
case 1:
{
input(name, shopNumber, brandShop, floor, shoptype);
shopList->Insert(name, shopNumber, brandShop, floor, shoptype);
}
break;
case 2:
{
string name1;
cin.clear();
cin.ignore();
cout << "Enter Name of Shop to Search: ";
getline(cin, name1);
shopList->search(name1);
}
break;
case 4:
{
shopList->Print();
}
break;
case 5:
{
shopList->~ShoppingMallList();
exit(0);
}
break;
default:
continue;
}
system("pause");
shopList;
} while (true);
return 0;
}
void input(string& name, int& shopNumber, string& brandShop, int& floor, string& shoptype)
{
char temp;
cin.clear();
cin.ignore();
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Shop Number: ";
cin >> shopNumber;
cin.clear();
cin.ignore();
cout << "Enter Brand(yes/no): ";
getline(cin, brandShop);
cout << "Enter Floor: ";
cin >> floor;
cin.clear();
cin.ignore();
cout << "Enter Shop Type: ";
getline(cin, shoptype);
}
Here is shoppingMall.h
class ShoppingMall
{
friend std::ostream& operator<<(std::ostream& cout, const ShoppingMall& shop);
friend class ShoppingMallList;
public:
ShoppingMall(std::string& , int&, std::string&, int&, std::string&);
private:
std::string name;
int shopNumber;
std::string brandshop;
int floor;
std::string shopType;
ShoppingMall* link;
};
ShoppingMall::ShoppingMall(std::string& name , int& shopNumber, std::string& brandShop, int& floor, std::string& shoptype) : name(name), shopNumber(shopNumber), brandshop(brandShop), floor(floor), shopType(shoptype)
{
}
std::ostream& operator<<(std::ostream& cout, const ShoppingMall& shop)
{
cout << "Name: " << shop.name << std::endl << "Shop Number: " << shop.shopNumber << std::endl << "Brand Shop: " << shop.brandshop << std::endl << "Floor: " << shop.floor << std::endl << "Shop Type: " << shop.shopType << std::endl;
return cout;
}
And here is ShoppingMallList.h header file.
class ShoppingMallList
{
public:
ShoppingMallList();
void addToHead(std::string&, int&, std::string&, int&, std::string&);
void Insert(std::string&, int&, std::string&, int&, std::string&);
void Print();
int getsize();
void deleteShop(std::string&);
void search(std::string&);
private:
ShoppingMall* head;
int size;
};
ShoppingMallList::ShoppingMallList() : head(0), size(0)
{
}
void ShoppingMallList::addToHead(std::string& name, int& shopNumber, std::string& brandShop, int& floor, std::string& shoptype)
{
ShoppingMall* temp = new ShoppingMall(name,shopNumber,brandShop,floor,shoptype);
if (head==0)
{
head = temp;
}
else
{
temp->link = head;
head = temp;
}
size++;
}
int ShoppingMallList::getsize()
{
return size;
}
void ShoppingMallList::Print()
{
ShoppingMall* temp = head;
while ( temp != 0 )
{
std::cout << "Name: " << temp->name << std::endl << "Shop Number: " << temp->shopNumber << std::endl << "Brand Shop: " << temp->brandshop << std::endl << "Floor: " << temp->floor << std::endl << "Shop Type: " << temp->shopType << std::endl;
temp = temp->link;
}
}
void ShoppingMallList::Insert(std::string& name, int& shopNumber, std::string& brandShop, int& floor, std::string& shoptype)
{
ShoppingMall* newShop = new ShoppingMall(name, shopNumber, brandShop, floor, shoptype);
//case-1 EmptyList
if ( head == 0 )
{
head = newShop;
}
else
{
ShoppingMall* temp = head;
ShoppingMall* previous = 0;
// Traversing link to find insert location
while (temp!=0)
{
if ( temp->name >= newShop->name )
{
break;
}
else
{
previous = temp;
temp = temp->link;
}
}
//case-2 Adding To Head
if ( temp == head )
{
newShop->link = head;
head = newShop;
}
//case-3 Adding After Head
else
{
newShop->link = temp;
previous->link = newShop;
}
}
size++;
}
void ShoppingMallList::deleteShop(std::string& name)
{
ShoppingMall* temp=head;
ShoppingMall* previous = 0;
if (head == 0)
{
//Case-1 If There is no node
std::cout << "Shop cannot be deleted becasue the there no Node " << std::endl;
}
//Traversing Node to find node to delete
while (temp!=0)
{
if ( temp->name == name )
{
break;
}
else
{
previous = temp;
temp = temp->link;
}
}
//case-2 If Shop with name passed not found
if ( temp == 0 )
{
std::cout << "Shop of name " << name << " not found!" << std::endl;
}
else
{
//case-3 Delete node from head Node
if ( temp == head )
{
head = head->link;
}
//delete other than head shop
else
{
previous->link = temp->link;
}
delete temp;
size--;
}
}
void ShoppingMallList::search(std::string& name)
{
ShoppingMall* tempShop = head;
while ( tempShop != 0 )
{
if (tempShop->name == name)
{
std::cout << "Name: " << tempShop->name << std::endl << "Shop Number: " << tempShop->shopNumber << std::endl << "Brand Shop: " << tempShop- >brandshop << std::endl << "Floor: " << tempShop->floor << std::endl << "Shop Type: " << tempShop->shopType << std::endl;
}
else
{
tempShop = tempShop->link;
}
}
if ( tempShop == 0 )
{
std::cout << "Shop of name " << name << " not found!" << std::endl;
}
}
link field of ShoppingMall class is not initialized in constructor and contains some random rubbish. All list iterations like:
while ( temp != 0 )
{
// Code skipped for simplicity
temp = temp->link;
}
could cause Access Violation because condition temp != 0 never met and skipped code access memory at random address.
To fix it:
ShoppingMall::ShoppingMall(const std::string& name, int shopNumber, std::string& brandShop, int floor, const std::string& shoptype)
: link(nullptr), name(name), shopNumber(shopNumber), brandshop(brandShop), floor(floor), shopType(shoptype)
{
}

undefined reference to (function) c++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Undefined Reference to
I've been banging my head against this one set of error messages for about 4 hours now and I can't seem to figure it out. I've not posted here before, so I apologize in advance if it's not in the right area or I've done something wrong. At any rate, the error messages I'm receiving are:
main.cpp|28|undefined reference to `LinkedSortedList<Employee>::LinkedSortedList()'|
main.cpp|52|undefined reference to `empPrint(LinkedSortedList<Employee>&)'|
main.cpp|58|undefined reference to `empSave(LinkedSortedList<Employee>&, std::string)'|
main.cpp|65|undefined reference to `empLoad(LinkedSortedList<Employee>&, std::string)'|
main.cpp|70|undefined reference to `LinkedSortedList<Employee>::~LinkedSortedList()'|
main.cpp|70|undefined reference to `LinkedSortedList<Employee>::~LinkedSortedList()'|
obj\Debug\main.o||In function `Z9empSearchR16LinkedSortedListI8EmployeeE':|
main.cpp|109|undefined reference to `LinkedSortedList<Employee>::getHead()'|
My main.cpp is as follows:
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include "SortedList.h"
#include "LinkedSortedList.h"
#include "Employee.h"
#include "LinkedNode.h"
using namespace std;
void newEmp(LinkedSortedList <Employee>& empList);
void empSearch(LinkedSortedList <Employee>& empList);
void empPrint(LinkedSortedList <Employee>& empList);
void empSave(LinkedSortedList <Employee>& empList, string file);
void empLoad(LinkedSortedList <Employee>& empList, string file);
int main()
{
//int empID;
bool menuFinish = false;
LinkedSortedList<Employee> empList;
char selection;
while (!menuFinish)
//simple menu system through cout, the selection is read in through cin
//and converted to upper case for simplicity during the conditionals
cout << "Menu" << endl;
cout << "(I)nsert new record" << endl;
cout << "(E)mployee ID search" << endl;
cout << "(P)rint employee info" << endl;
cout << "(S)ave database to a file" << endl;
cout << "(L)oad database from file" << endl;
cout << "(Q)uit" << endl;
cout << "Enter selection " << endl;
cin >> selection;
selection = toupper(selection);
//menu selections are compared with their functions
if (selection == 'I')
newEmp(empList);
else if (selection == 'E')
empSearch(empList);
else if (selection == 'P')
empPrint(empList);
else if (selection == 'S')
{
string fileName;
cout << "Enter a filename to save the database to " << endl;
cin >> fileName;
empSave(empList, fileName);
}
else if (selection == 'L')
{
string fileName;
cout << "Enter the filename to load the database from " << endl;
cin >> fileName;
empLoad(empList, fileName);
}
else if (selection == 'Q')
menuFinish = true;
else
cout << "Incorrect choice " << endl;
}
//function creates a new employee
void newEmp(LinkedSortedList <Employee>& empList)
{
string firstName;
string lastName;
int empID = -1;
cout << "Please enter the first name " << endl;
cin >> firstName;
cout << "Please enter the last name " << endl;
cin >> lastName;
while (empID > 9999999 || empID < 0)
{
cout <<"Please enter the employee ID " << endl;
cin >> empID;
}
//puts the employee in the db unless they're already found, then outputs an
//error on the screen
Employee emp(firstName, lastName, empID);
bool findEmp = empList.find(emp);
if (!findEmp)
empList.insert(emp);
else
cout << "Emlpoyee ID " << empID << " already in use " << endl;
}
//function to search for an employee based on their employee ID
void empSearch (LinkedSortedList <Employee>& empList)
{
int empID;
int sizeOfList = 0;
bool noEmp = true;
cout << "Enter employee ID " << endl;
cin >> empID;
LinkedNode <Employee>* temp = empList.getHead();
while (sizeOfList < empList.size() && noEmp)
{
sizeOfList++;
if (empID == temp->value.getEmpID())
{
cout << "Searched " << sizeOfList << "employees " << endl;
cout << "Found record: " << temp->value;
noEmp = false;
}
temp = temp->next;
}
if (noEmp)
cout << "Search of " << sizeOfList << " employees. Employee not found" << endl;
}
//function used to print the first and last five employees from the db
void empPrint (LinkedSortedList <Employee>& empList)
{
if (empList.size() <= 10)
{
empList.print();
}
else
{
LinkedNode<Employee>* temp = empList.getHead();
cout << "First five employees: " << endl;
for (int i = 0; i < 5; i++)
{
cout << temp->value << endl;
i++;
temp = temp->next;
}
int midList = empList.size()-5;
for (int i = 0; i < midList; i++)
{
temp = temp->next;
}
cout << "Last five employees: " << endl;
for (int i = 0; i < 5; i++)
{
cout << temp->value << endl;
i++;
temp = temp->next;
}
}
}
//function used to save the employee information from the db to a file
void empSave(LinkedSortedList<Employee>& empList, string fileName)
{
string lastName;
string firstName;
//int empID;
ofstream output;
output.open(fileName.c_str());
if (!output)
{
cout << "File not saved" << endl;
}
else
{
LinkedNode<Employee>* temp = empList.getHead();
int i = 0;
while (i < empList.size())
{
output << temp->value.getLastName() << " " << temp->value.getFirstName() << " " << temp->value.getEmpID() << endl;
i++;
temp = temp->next;
}
}
output.close();
}
//function used to load the employee information from a file to the db
void empLoad(LinkedSortedList<Employee>& empList, string fileName)
{
if (empList.size() > 0)
{
empList.clear();
}
ifstream input;
input.open(fileName.c_str());
if (!input)
{
cout << "No file exists" << endl;
}
else
{
int empID;
string firstName;
string lastName;
string delimiter;
while(input.good());
{
getline(input, delimiter, '\n');
getline(input, lastName, ' ');
getline(input, firstName, ' ');
input >> empID;
Employee emp(lastName, firstName, empID);
bool empFound = empList.find(emp);
if(!empFound)
{
empList.insert(emp);
}
else
cout << "Employee already exists" << endl;
}
}
}
My LinkedSortList.cpp is:
#ifndef _LinkedSortedList_
#define _LinkedSortedList_
#include "Employee.h"
#include "LinkedSortedList.h"
#include "SortedList.h"
#include "LinkedNode.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//default constructor
//sets head to null and makes the size of the list 0
template <class Elem>
LinkedSortedList<Elem>::LinkedSortedList()
{
head = NULL;
listSize = 0;
}
//destructor, clears list THEN deletes the head so memory leaks are
//stopped
template <class Elem>
LinkedSortedList<Elem>::~LinkedSortedList()
{
clear();
delete head;
}
//clears the list, freeing memory and stopping leaks and resets the
//list size
template <class Elem>
void LinkedSortedList<Elem>::clear()
{
LinkedNode<Elem> *indexPtr = head;
while (head != NULL)
{
head = head->next;
delete indexPtr;
indexPtr = head;
}
listSize = 0;
}
//finds a search value in the list... if it finds it then it returns true,
//otherwise it returns false
template <class Elem>
bool LinkedSortedList<Elem>::find(Elem searchValue) const
{
LinkedNode<Elem>* indexPtr = head;
while (indexPtr != NULL)
{
if (indexPtr->value == searchValue)
{
return true;
}
indexPtr = indexPtr->next;
}
return false;
}
//gets and DELETES first value in the list - if it finds nothing then
//return false, otherwise true
template <class Elem>
bool LinkedSortedList<Elem>::getFirst(Elem &returnValue)
{
LinkedNode<Elem>* indexPtr = head;
if (indexPtr == NULL)
return false;
else
{
head = head->next;
returnValue = indexPtr->value;
delete indexPtr;
listSize--;
return true;
}
returnValue = indexPtr->value;
}
//prints the list to cout or prints a warning if the list contains
//no values
template <class Elem>
void LinkedSortedList<Elem>::print() const
{
if (head == NULL)
{
cout << "No elements in the list" << endl;
}
else
{
LinkedNode<Elem>* indexPtr = head;
while (indexPtr != NULL)
{
cout << indexPtr->value << endl;
indexPtr = indexPtr->next;
}
}
}
//returns the size of the list to the caller
template <class Elem>
int LinkedSortedList<Elem>::size() const
{
return listSize;
}
//inserts a value into the list where it should go, if the list is empty it will
//say there are no existing nodes
template <class Elem>
bool LinkedSortedList<Elem>::insert(Elem newValue)
{
LinkedNode<Elem>* indexPtr = head;
LinkedNode<Elem>* newNode;
//newNode->value = newValue;
try
{
newNode = new LinkedNode<Elem>(newValue);
}
catch(exception e)
{
cout<<"Exception reached: " << e.what() << endl;
return false;
}
//checks to see if the list is empty, if it is then it makes the newNode
//the head
if (head == NULL)
{
cout << "No existing nodes" << endl;
head = newNode;
cout << "First node is now " << head->value << endl;
listSize++;
return true;
}
/*looks to see if the value of the newNode is less than or equal to the
index, if it is then it sets the point of the newNode equal to the head
then makes the head the newNode and increments the listSize by one to keep
track of the size of the list and returns true*/
else if (newNode->value <= head->value)
{
newNode->next = head;
head = newNode;
listSize++;
return true;
}
/*if the newNode value is greater than the index, then:*/
else
{
while(indexPtr->next != NULL && newNode->value > indexPtr->next->value)
{
indexPtr = indexPtr->next;
}
if (indexPtr->next == NULL)
{
indexPtr->next = newNode;
listSize++;
return true;
}
else
{
newNode->next = indexPtr->next;
indexPtr->next = newNode;
listSize++;
return true;
}
}
}
//added for project 2 to return the head of the LL
template <class Elem>
LinkedNode<Elem>* LinkedSortedList<Elem>::getHead()
{
return head;
}
#endif
The Employee.cpp is:
#ifndef _Employee_
#define _Employee_
#include "Employee.h"
#include "LinkedSortedList.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//blank default constructor
Employee::Employee()
{
}
//constructor that takes 3 parameters and sets them
Employee::Employee(string lastName, string firstName, int eID)
{
this->lastName = lastName;
this->firstName = firstName;
this->empID = eID;
}
//blank deconstructor
Employee::~Employee()
{
}
//overloaded equality operator
bool Employee::operator==(Employee &nextEmployee)
{
if (this->empID == nextEmployee.empID)
return true;
else
return false;
}
//overloaded less than or equal to operator
bool Employee::operator <= (Employee &nextEmployee)
{
if (this->empID <= nextEmployee.empID)
return true;
else
return false;
}
//overloaded greater than or equal to operator
bool Employee::operator >= (Employee &nextEmployee)
{
if (this->empID >= nextEmployee.empID)
return true;
else
return false;
}
//overloaded less than operator
bool Employee::operator < (Employee &nextEmployee)
{
if (this->empID < nextEmployee.empID)
return true;
else
return false;
}
//overloaded greater than operator
bool Employee::operator > (Employee &nextEmployee)
{
if (this->empID > nextEmployee.empID)
return true;
else
return false;
}
// overloaded output stream operator
ostream& operator<<(ostream& os, const Employee empl)
{
os << "Last: " << empl.lastName << endl;
os << "First: " << empl.firstName << endl;
os << "Employee ID: " << empl.empID << endl;
return os;
}
#endif
My header file, LinkedSortedList.h:
#ifndef _LinkedSortedListClass_
#define _LinkedSortedListClass_
#include "SortedList.h"
#include "LinkedNode.h"
#include <iostream>
#include <fstream>
#include <string>
//using namespace std;
template <class Elem>
class LinkedSortedList : public SortedList< Elem >
{
public:
LinkedSortedList();
~LinkedSortedList();
virtual void clear();
virtual bool insert(Elem newValue);
virtual bool getFirst(Elem &returnValue);
virtual void print() const;
virtual bool find(Elem searchValue) const;
virtual int size() const;
LinkedNode<Elem>* getHead(); //added for project 2
private:
LinkedNode<Elem>* head;
int listSize;
};
#endif
And finally (WHEW!) my Employee.h is here:
#ifndef _EmployeeClass_
#define _EmployeeClass_
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Employee
{
public:
Employee();
~Employee();
Employee(string, string, int);
bool operator == (Employee& nextEmployee);
bool operator <= (Employee &nextEmployee);
bool operator >= (Employee &nextEmployee);
bool operator < (Employee &nextEmployee);
bool operator > (Employee &nextEmployee);
friend ostream& operator<<(ostream& os, const Employee empl);
string getLastName(){return lastName;}
string getFirstName(){return firstName;}
int getEmpID(){return empID;}
private:
string lastName;
string firstName;
int empID;
};
#endif
I'm just not seeing the problem here, I've spoken to my TA, the helproom staff and other students. I haven't heard back from the prof yet, but I doubt I'll hear from her this weekend anyway. Thank you VERY much for any insight you can provide. I need some tylenol.
-Josh
How are you compiling your code? If you are using an IDE such as Microsoft Visual C++, be sure to create a project and add all of your .cpp files (not your .h files) to it. If you are using the command-line, be sure to include all of your filenames as command-line arguments. If this still doesn't help. Please include a description of the steps you are using to compile the program.
Edit:
There are several issues with your code:
#ifndef ... #define... include guards are meant for files which will appear in #include directives in other files. Typically these are only .h files since it is strongly discouraged to #include .cpp files.
Classes which use templates must all be in one .h file, not separated into a .h and .cpp file. (READ: In case I haven't made this clear enough, your LinkedSortedList class must ALL be in one .h file.)
Your main.cpp file declares several functions which are not later defined. If you don't want to take the time to implement these functions yet, you need to at least add empty stubs for them.
Be sure to compile and link all of your source files using a project in your IDE or using the correct command-line arguments. This is what I described in my original answer above.
To get templates instantiated automatically the compiler needs to the see the definition at the point of use. If you don't want to make the template definition visible you need to use explicit instantiation. How to do either of these is frequently answered.
BTW, please don't use names reserved for the implementation of the C++ compiler and its standard library as include guards: names starting with an underscore followed by a capital letter are reserved in all contexts for the C++ implementation.
My LinkedSortList.cpp is ...
That's the source of most of your problems. Doing what you did doesn't make sense. You need to define those inline in your header file, LinkedSortedList.h. That covers most of your problems the others, where are you defining empPrint(LinkedSortedList<Employee>&)?
First of all I cant see definition of these three:-
void empPrint (LinkedSortedList <Employee>& empList);
void empSave (LinkedSortedList <Employee>& empList, string file);
void empLoad (LinkedSortedList <Employee>& empList, string file);
Hope implementing them will reduce the errors.
C++ template methods and functions are not turned into machine code until the compiler runs into a call to the function with a specific type. But that means that the code that defines a template method, for example all of LinkedSortedList.cpp, actually does not produce any code at all when the compiler sees it.
You need to move all of the code from LinkedSortedList.cpp into LinkedSortedList.h (and similarly for the other templated classes) so that the compiler can produce the code for these methods when they are called. For example the compiler will generate the code for LinkedSortedList::LinkedSortedList() when it is called in main.cpp, but only if it's already seen the definition for this method in a header file.
Your other option is to use 'explicit instantiation' to force particular versions of particular methods to be compiled into object code.

C++ why does my array not pop into my stack?

I created an array for studentrecords and am supposed to pop it into my stack.. well everything works except for my stack.pops and stack.pushes in MAIN...I am so close to finishing this program I am wondering if anyone knows any solutions?
#include <iostream>
#include <list>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <string>
using namespace std;
class Studentrecords
{
private:
struct student
{
string name;
string address;
int ID;
double gpa;
};
student *stackArray;
int stackSize;
int top;
public:
Studentrecords();
Studentrecords(int size);
~Studentrecords();
void push(string name, string address, int id, double gpa);
void pop();
bool isFull() const;
bool isEmpty() const;
void display();
};
Studentrecords::Studentrecords(int size)
{
stackArray = new student[size];
top = -1;
}
Studentrecords::Studentrecords()
{
stackSize = 20;
stackArray = new student[stackSize];
top = -1;
}
Studentrecords::~Studentrecords()
{
delete [] stackArray;
}
void Studentrecords::push (string name, string address, int id, double gpa)
{
if (isFull())
{
cout << "The stack is full!" << endl;
}
else
{
student newStudent;
newStudent.name = name;
newStudent.address= address;
newStudent.ID = id;
newStudent.gpa = gpa;
stackArray[top] = newStudent;
top++;
}
}
void Studentrecords::pop ()
{
if (isEmpty())
{
cout << "The stack is empty!" << endl;
}
else
{
cout << stackArray[top-1].name << endl;
cout << stackArray[top-1].address << endl;
cout << stackArray[top-1].ID << endl;
cout << stackArray[top-1].gpa << endl;
top--;
}
}
bool Studentrecords::isFull() const
{
bool status;
if (top == stackSize - 1)
status = true;
else
status = false;
return status;
}
bool Studentrecords::isEmpty() const
{
bool status;
if (top == -1)
status = true;
else
status = false;
return status;
}
void Studentrecords::display()
{
for (int i = 0; i< top; i++)
{
cout << stackArray[i].name << endl;
cout << stackArray[i].address << endl;
cout << stackArray[i].ID << endl;
cout << stackArray[i].gpa << endl << endl;
}
}
int main()
{
int catchVar;
Studentrecords stack();
cout << "Pushing 1st";
stack.push("Jonny", "123 ave", 2343, 3.2);
cout << "pushing 2nd";
stack.push("Robby", "123 ave", 2343, 3.2);
cout << "Popping ";
stack.pop(catchVar);
cout << catchVar << endl;
cout << "Popping ";
stack.pop(catchVar);
cout << catchVar << endl;
return 0;
}
Studentrecords stack();
Does not declare a Studentrecords named stack, it declares a function named stack that returns a Studentrecords. Change it to
Studentrecords stack;
Also your class needs at least a copy constructor and assignment operator.
Can you post the compiler's error?
Or the produced output VS the expected output?
Without that, I'll have to say that your pop function doesn't take arguments and you are passing it catchVar... that would be a compiler error.