class variable getting altered by code that were seemingly not executed - c++

So I'm doing this singly linked list implementation for an school assignment. A struct of "evaluation" was defined in the header file and a object of "mylinkedlist" would hold the pointer to the head of the linked list. This should be an easy project but for some reason, whenever I try to call the add function, the head pointer was altered despite a) not being called and b) the head pointer was seemingly altered before the add function was even called
below is a minimum repro of the problem
//header file
#pragma once
#ifndef MYLINKEDLIST_H
#define MYLINKEDLIST_H
#include <iostream>
#include <process.h>
using namespace std;
const int maxSize = 20; // size string
struct Evaluation
{
char student[maxSize] = { 'a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t' };
int grade;
Evaluation *next;
};
class myLinkedList {
private:
Evaluation *head;
public:
myLinkedList(Evaluation *);
Evaluation *add(Evaluation *, int &);
Evaluation * returnHead();
};
#endif#pragma once
//mylinkedlist.cpp
#include "pch.h"
#include "myLinkedList.h"
#include <iostream>
#include <string>
myLinkedList::myLinkedList(Evaluation *h) {
this->head = h;
}
Evaluation * myLinkedList::returnHead() {
return this->head;
}
Evaluation * myLinkedList::add(Evaluation *c, int &b) {//a is the first element
Evaluation *pointer = this->head;
cout << "head in the beginning " << this->head->grade << endl;
cout << "pointer in the beginning " << pointer->grade << endl;
bool y = b == 0;
cout << "b==0 " << y << endl;
if (b == 0) {
pointer = this->head;
this->head = c;
this->head->next = pointer;
cout << "head after if " << this->head->grade << endl;
}
return this->head;
}
//main
#include "pch.h"
#include "myLinkedList.h"
#include <iostream>
#include <string>
int main() {
Evaluation *first = new Evaluation();
int choice;
int grade = 0;
int number = 0;
first->grade = 20;
myLinkedList *list = new myLinkedList(first);
cout << "list head is " << list->returnHead()->grade << endl;
Evaluation *tempt = new Evaluation();
do
{
cout << "please enter the grade of student : ";
cin >> grade;
cout << "list head is 2nd " << list->returnHead()->grade << endl;
tempt->grade = grade;
cout << "list head is 3rd " << list->returnHead()->grade << endl;
list->add(tempt, number); // added element, index
number++;
} while (true);
return 0;
}
See how the head was changed between "list head is 2nd" and "list head is 3rd" despite the head not being called. And another strange thing was that if i remove the add function or the call to the add function , the problem would disappear despite the call to the add function coming after the couts.
And inside the add method, the if statement seemed to be the problem once again despite being coming after the cout line and not executing (the b==0 outputting false). The only way i knew that it has something to do with the persisting problem is that if i delete it the problem went away.

The same node assigned to tempt is repeatedly added, so modifying the node will affect other references of the node.
It seems you want to allocate new nodes for each input. To do that, allocate new elements inside the loop.
// remove this
//Evaluation *tempt = new Evaluation();
do
{
// and move here (inside the loop)
Evaluation *tempt = new Evaluation();
cout << "please enter the grade of student : ";
cin >> grade;
cout << "list head is 2nd " << list->returnHead()->grade << endl;
tempt->grade = grade;
cout << "list head is 3rd " << list->returnHead()->grade << endl;
list->add(tempt, number); // added element, index
number++;
} while (true);

Related

"Undefined reference to 'std::operator<<(std::ostream&, std::LinkedList const&)" C++

hi guys this is a uni project and at the moment have encountered this issue which comes up during compilation
/usr/lib/gcc/x86_64-pc-cygwin/9.3.0/../../../../x86_64-pc-cygwin/bin/ld: LinkedListDemo.o:LinkedListDemo.cpp:(.text+0x178): undefined reference to std::operator<<(std::ostream&, std::LinkedList const&)' LinkedListDemo.o:LinkedListDemo.cpp:(.text+0x178): relocation truncated to fit: R_X86_64_PC32 against undefined symbol std::operator<<(std::ostream&, std::LinkedList const&)'
collect2: error: ld returned 1 exit status
make: *** [makefile:11: a1] Error 1
#include <iostream>
#include <cstdlib>
#include <string>
#include "LinkedList.h"
using namespace std;
void initialize(LinkedList &l1, LinkedList &l2)
{
l1.add("the black cat was sitting on the black mat that was on the black floor");
l2.add("the dog scared the cat and the cat ran away");
}
int main()
{
LinkedList firstList;
LinkedList secondList;
initialize(firstList, secondList);
cout << "Start lists:" << endl;
cout << "List 1: " << firstList << endl;
//cout << "List 2: " << secondList << endl << endl;
cout << "Concatenating the two lists onto list '1':" << endl;
firstList += secondList;
// cout << "List 1: " << firstList << endl;
//cout << "List 2: " << secondList << endl << endl;
cout << "Removing the word 'was' from list '1':" << endl;
firstList.remove("was");
// cout << "List 1: " << firstList << endl;
//cout << "List 2: " << secondList << endl << endl;
cout << "Removing the word 'away' from list '2':" << endl;
secondList.remove("away");
// cout << "List 1: " << firstList << endl;
//cout << "List 2: " << secondList << endl << endl;
cout << "Removing the word 'cat' from both lists:" << endl;
firstList.remove("cat");
secondList.remove("cat");
//cout << "List 1: " << firstList << endl;
//cout << "List 2: " << secondList << endl << endl;
cout << "Number of occurrences of 'black' in list 1: ";
cout << firstList.count("black") << endl << endl;
// Uncomment this section if you are implementing the extended version of the method remove()
// cout << "Removing 'on the black' from both lists:" << endl;
// firstList.remove("on the black");
// secondList.remove("on the black");
// cout << "List 1: " << firstList << endl;
// cout << "List 2: " << secondList << endl << endl;
cout << "Sorting list 1:" << endl;
firstList.sort();
//cout << firstList << endl << endl;
cout << "The program has finished." << endl;
return 0;
}
that is the main file which is meant to work and not be changed
#ifndef will_PC
#define will_PC
#include <cstdlib>
#include <string>
#include "node.h"
namespace std{
class LinkedList{
public:
node* get_Head() const;
void add(string input);
void remove(string Input);
void sort();
int count(string Input);
string getText();
void operator += (const LinkedList& list);
private:
node* head;
node* tail;
node* n;
};
//this is what outputs the object
std::ostream& operator << ( std::ostream &out, LinkedList const& lst);
}
#endif
#include <iostream>
#include <cstdlib>
#include <string>
#include "LinkedList.h"
using namespace std;
void LinkedList::add(string Input){
tail = NULL;
int count =0;
string word = "";
int len=Input.length();
for (int i=0; i< len;i++)
{
if (Input[i]==' ')
{
n = new node;
n->set_Data(word);
n->set_Previous(tail);
n->set_Next(NULL);
if(tail !=NULL){
tail->set_Next(n);
}
tail = n;
if (count ==0)
{
head = n;
}
word = "";
count +=1;
} else
{
word +=Input[i];
}
}
n = new node;
n->set_Data(word);
n->set_Previous(tail);
n->set_Next(NULL);
tail = n;
}
void LinkedList::remove(string Input){
node* temp;
node* hold;
temp =head;
while (temp!=NULL){
if(Input.compare(temp->get_Data())==0){
hold = temp->get_Next();
temp=temp->get_Previous();
temp->set_Next(hold);
hold->set_Previous(temp);
temp=temp->get_Next();
temp=temp->get_Next();
} else{
temp = temp->get_Next();
}
}
}
int LinkedList::count(string Input){
node* temp;
temp =head;
int count= 0 ;
while (temp != NULL){
if(Input.compare(temp->get_Data())==0){
count +=1;
}
temp = temp->get_Next();
}
return count;
}
void LinkedList::operator += (const LinkedList& list){
node* temp;
cout << list.get_Head()->get_Next()->get_Data()<<endl;
temp = list.get_Head();
while(temp!=NULL){
n=new node;
n->set_Data(temp->get_Data());
n->set_Previous(tail);
n->set_Next(NULL);
tail->set_Next(n);
tail= n;
temp=temp->get_Next();
}
}
void LinkedList::sort(){
node* temp;
temp =head;
while(temp!=NULL){
cout<<temp->get_Data()<<" ";
temp = temp->get_Next();
}
cout<<endl;
}
node* LinkedList::get_Head() const {
return head;
}
std::ostream& operator << ( std::ostream &out, LinkedList const& lst)
{
node* temp = lst.get_Head();
while(temp != NULL){
out<< " "<< temp->get_Data() <<" ";
temp = temp->get_Next();
}
return out;
}
#include <cstdlib>
#include <string>
#include "node.h"
using namespace std;
void node::set_Next(node* nextLink){
next = nextLink;
}
void node::set_Previous(node* previousLink){
previous = previousLink;
}
node* node::get_Next(){
return next;
}
node* node::get_Previous(){
return previous;
}
void node::set_Data(string input){
text = input;
}
string node::get_Data(){
return text;
}
#ifndef Will_Node
#define Will_Node
#include <cstdlib>
#include <string>
namespace std{
class node{
public:
void set_Next(node* nextLink);
void set_Previous(node* previousLink);
void set_Data(string input);
node* get_Next();
node* get_Previous();
string get_Data();
private:
string text;
node* next;
node* previous;
};
}
#endif
any help is greatly appreciated ive spent way too many hours cursing to try and fix this
You declare your operator << in namespace std (which is illegal, as noted in comments), but you define it in global namespace.
using namespace works with definitions of class methods, because compiler knows that there is a class LinkedList in namespace std, so it can connect it:
If add() is a member of LinkedList, and LinkedList is a member of namespace std, then the fully qualified name must be ::std::LinkedList::add()
But the operator is a free function, so the compiler has nothing to relate it to the previous declaration and it is placed in global namespace.
Solution:
Change your namespace to something different than std
Instead of adding using namespace in cpp files, wrap the whole content in namespace{} :
#include <iostream>
#include <cstdlib>
#include <string>
#include "LinkedList.h"
namespace X {
void LinkedList::add(string Input){
// all of the member definitions...
std::ostream& operator << ( std::ostream &out, LinkedList const& lst)
{
node* temp = lst.get_Head();
while(temp != NULL){
out<< " "<< temp->get_Data() <<" ";
temp = temp->get_Next();
}
return out;
}
} // namespace X
//file ends here
You could also wrap only your operator definition in namespace {}, but it's easier to avoid such issues if you by default put whole content in namespace.

My dynamically linked queue improperly outputs three return functions when called in the same output stream

For an assignment I was tasked with creating a queue with linked lists. Our professor has given us the test code to insure the program is working properly and for grading. My serve function returns a character. However in the main(), the function is called twice within one cout statement, and it returns the character in incorrect order. The getSize function is also called, however it does not seem to do anything.
cout << boolalpha;
Queue q1 = Queue();
q1.append('m');
q1.append('a');
q1.append('b');
q1.append('b');
q1.display();
cout << q1.serve() << " " << q1.serve() << " " << q1.getSize() << endl;
the display outputs: m a b b. However the cout shows as: a m 4. This should obviously come out as: m a 2.
If i separate the serve and the getSize functions, it works just fine, i.e. cout << q1.serve() << " "; cout << q1.serve() << " "; cout << q1.getSize() << " ";
Below I have posted the code for the linked queue. I imagine I have made a mistake with my node pointers, however I have drawn pictures and re-written the code to no avail.
I also apologize if Ive improperly formatted this as it is my first posting. Thank you.
#include <iostream>
using namespace std;
struct Node {
char data;
Node* next;
};
class Queue {
private:
Node* front, * rear;
int size;
public:
Queue();
void append(char);
char serve();
bool isEmpty();
bool isFull();
int getSize();
void display();
};
Queue::Queue() {
front = rear = nullptr;
size = 0;
}
void Queue::append(char v) {
Node* p = new Node;
p->data = v;
p->next = nullptr;
if (size == 0) {
front = rear = p;
size++;
}
else if (size == 1) {
front->next = p;
rear = p;
size++;
}
else {
rear->next = p;
rear = p;
size++;
}
}
char Queue::serve() {
if (front != nullptr) {
Node* temp = front;
char v = temp->data;
front = front->next;
delete temp;
size--;
return v;
}
}
bool Queue::isEmpty() {
return size == 0;
}
bool Queue::isFull() {
return false;
}
int Queue::getSize() {
return size;
}
void Queue::display() {
Node* runner = front;
while (runner != nullptr) {
cout << runner->data << " ";
runner = runner->next;
}
cout << endl;
}
int main() {
cout << boolalpha;
Queue q1 = Queue();
q1.append('m');
q1.append('a');
q1.append('b');
q1.append('b');
q1.display();
cout << endl << q1.isEmpty() << " " << q1.isFull() << " " << q1.getSize() << endl;
cout << q1.serve() << " " << q1.serve() << " " << q1.getSize() << endl;
q1.display();
cout << endl;
/*cout << q1.isEmpty() << " " << q1.isFull() << " " << q1.getSize() << endl;
char a = q1.serve(); char b = q1.serve();
cout << a << " " << b << " " << q1.getSize() << endl;*/
}
I'll give you a big hint: Your output is "a m 4", not "m a 4". The remainder of the answer is below...
.
.
.
.
.
.
(edit: added more explanation)
The cout is running the arguments right to left, because of the associativity of the << operator. So it's getting the size, then getting the first item in the queue, then getting the next one. Even though the operator itself is Left-to-Right, in order to apply them in that order, it's evaluating the arguments right to left.
Think of it this way, while it's required to apply the operators on the left before it applies the ones on the right, it's still evaluating the argument on the right of the operator before it evaluates the one on the left.
This is fundamentally about how the stack works. It's loading the evaluation of the arguments and operators right to left so that it can apply the operators in the reverse order.
Since the operators are all the same precedence, it's pushing the right most operand, then the right most operator, then that' operator's left operand, which is everything to the left.
If your operators are L-R associative, that means that the operands are evaluated R-L before being operated on L-R.
Just do
cout << q1.serve() << " ";
cout << q1.serve() << " ";
cout << q1.getSize() << endl;

Error when converting a linked list into an array of pointers

This is the program prompt:
Write a C++ program to process periodic table information from a file. Each element will have an atomic number, a name, an abbreviation, and a mass. Your program must include:
An Element structure to be defined in a header file: Element.h
A function read_table that will return the number of elements read from the file and via a reference parameter, a pointer to an array of pointers to the elements read. The data file is located at /user/tvnguyen7/data/periodictable.dat. This function must read in the data by constructing a linked list and convert the linked list into an array of pointers. The prototype for this function is to be included in the Element.h file. The function will return 0 on any error condition.
A main program that will call read_table to read in the table, sort the table using the element name and print out the table using the required output format. You can use qsort in cstdlib or write your own sort function.
Dynamic memory must be allocated and deallocated properly.
This is what I have for periodic_table.cpp:
#include <iostream>
#include <cstdlib>
#include "Element.h"
#include <string>
#include <iomanip>
using namespace std;
int main() {
int count = 0;
Element **pt = new Element *[count];
cout << setw(30) << left << " Periodic Table by K. Nguyen" << endl;
cout << endl;
cout << setw(30) << " Number of elements: " << endl;
cout << endl;
cout << setw(5) << " Name" << right << setw(20) << "Abr" << setw(5) << " ANo" << setw(8) << "Mass" << endl;
cout << setw(20) << left << " --------------------" << setw(4) << right << "---" << setw(5) << "----" << setw(8) << "-------" << endl;
read_table(&count, pt);
delete [] pt;
return 0;
}
Here's what I have for read_table.cpp:
#include <fstream>
#include <iostream>
#include <string>
#include "Element.h"
using namespace std;
int read_table(int *count, Element **ppt){
struct Node {
Element *pElement;
Node *next;
};
int temp = 0;
int aNum;
string aBr;
double mass;
string name;
Node *n = nullptr;
Node *h = nullptr;
Node *t = nullptr;
ifstream infile;
infile.open("periodictable.dat");
while(infile >> aNum >> aBr >> mass >> name){
Element *e = new Element;
e->ANo = aNum;
e->Abr = aBr;
e->Mass = mass;
e->Name = name;
n = new Node;
n->pElement = e;
n->next = nullptr;
if(h == nullptr){
h = t = n;
}
else {
t->next = n;
t = n;
}
temp++;
}
infile.close();
int i = 0;
for(Node *x = h; x, i < temp; x = x->next, i++){
ppt[i] = x->pElement;
}
*count = temp;
return 0;
}
Here's what I have for Element.h:
#ifndef ELEMENT_H
#define ELEMENT_H
using namespace std;
struct Element {
int ANo;
string Abr;
double Mass;
string Name;
};
int read_table(int *count, Element **ppt);
#endif
I think the problem is in this for loop in read_table.cpp:
int i = 0;
for(Node *x = h; x, i < temp; x = x->next, i++){
ppt[i] = x->pElement;
}
and also I am not sure if I am passing in the array of pointers right or not (this is in periodic_table.cpp):
int count = 0;
Element **pt = new Element *[count];
....
read_table(&count, pt);
The error is:
In function 'main': periodic_table.cpp: undefined reference to 'read_table(int*, Element**)'
My program cannot run when I include that for loop; however, it runs fine without it so I think I am doing something wrong there but I don't know what. Please help.
If you're using Microsoft Visual Studio(The one I use the most for C++); go on Solution explorer; copy the path for read_table.cpp; right click on Source Files folder in the explorer, add existing item. Then paste the path on to it. Click OK then run your program again. It should work.

Can't find proper value to use without getting for insert function

I've been coding for a few hours today but seem to have thrown a blank. The assignment is creating a grocery list and adding in certain items to it while checking to see if the item is already in the list, if the list is empty and other things.
While working on the assignment, I can't find the proper value/variable to use in my insert function and it's killing me that something this small has stopped me from doing the assignment. The error is in my GroceryList.cpp file where all the functions are defined and all the code written out so that it removes, inserts, and checks for empty list. Everything else seems to compile just fine so far (I still need to fix some functions) but right now I'm trying to get my insert function to work. Can anyone look over my code and point me in the right direction for which value to use in my insert function? Did I even write the insert function properly? Thanks.
GroceryList.h
#ifndef GROCERYLIST_H
#define GROCERYLIST_H
#include <string>
using namespace std;
namespace CS151GroceryList
{
// node definition
struct ListNode
{
string item;
ListNode *link;
};
// define a type for pointers to nodes
typedef ListNode* ListNodePtr;
// define the GroceryList class
class GroceryList
{
public:
// default constructor initializes an empty list
GroceryList();
// destructor - destroys the list and returns all memory to the heap
~GroceryList();
// returns true if the list is empty; false otherwise
bool empty();
// check to see if an item is in the list. If so, return true. If not, return false.
bool inList(const string& an_item);
// prints all of the items in the list. If insert is implemented correctly, the contents
// of the list will be printed in alphabetical order with no repeats.
void print();
// if an_item is found, remove it from the list
void remove(const string& an_item);
// put a new item into the list. The item should be placed into the correct
// position in the list. If the item is already in the list, no change is
// made to the list. Note, you should put A COPY of an_item into the list
void insert(const string& an_item);
private:
ListNodePtr top;
};
} // end CS151GroceryList namespace
#endif GROCERYLIST_H
GroceryListTest.cpp This test the functions to make sure they work. Adds in specific grocery items to the list, spits out the list, and removes what is in the list. Problem not here
#include <iostream>
#include <string>
#include "GroceryList.h"
using namespace std;
using namespace CS151GroceryList;
int main()
{
GroceryList mylist;
/**********************************************************************
* List insertion test *
**********************************************************************/
cout << "Inserting items into the grocery list." << endl << endl;
mylist.insert("Eggs");
mylist.insert("Bananas");
mylist.insert("Wheat Bread");
mylist.insert("Peanut Butter");
mylist.insert("Milk");
mylist.insert("Apples");
mylist.insert("White Bread");
cout << "Finished inserting items." << endl;
cout << "Grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl;
/**********************************************************************
* inList test *
**********************************************************************/
cout << "Testing in list functionality:" << endl;
if (mylist.inList("Oranges"))
{
cout << "Oranges are on the list." << endl;
}
else
{
cout << "Oranges are not on the list." << endl;
}
if (mylist.inList("Apples"))
{
cout << "Apples are on the list." << endl;
}
else
{
cout << "Apples are not on the list." << endl;
}
if (mylist.inList("Peanut Butter"))
{
cout << "Peanut Butter is on the list." << endl;
}
else
{
cout << "Peanut Butter is not on the list." << endl;
}
if (mylist.inList("White Bread"))
{
cout << "White Bread is on the list." << endl;
}
else
{
cout << "White Bread is not on the list." << endl;
}
/**********************************************************************
* List removal test *
**********************************************************************/
cout << "Testing list removal." << endl;
cout << endl << "I decided that I didn't want apples after all. Removing apples." << endl;
mylist.remove("Apples");
cout << "After removing apples, grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl << endl;
cout << endl << "I decided that I didn't want white bread either. Removing white bread." << endl;
mylist.remove("White Bread");
cout << "After removing white bread, grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl << endl;
cout << endl << "I'm lactose intolerant, I'd better not get milk. Removing milk." << endl;
mylist.remove("Milk");
cout << "After removing milk, grocery list contents:" << endl;
mylist.print();
cout << endl << "Finished printing the list." << endl << endl;
}
GroceryList.cpp The error is in this file
To be exact the error is in this portion of the code. This is where each function gets called and all the inserting, removing, and checking happens. I have used an_item as a place holder so that I know where I need to figure out the proper value for the function. I have tried all of the pointers I currently have and other values. I even created a temp value(not shown here) but that didn't seem to work either.
void GroceryList::insert(const string& an_item)
{
if (top == an_item.insert)
{
return;
}
char next;
while (!empty())
{
delete(top);
}
if (an_item.insert == NULL)
{
top = NULL;
return;
}
ListNodePtr temp = new ListNode;
temp->item = an_item;
temp->link = top;
top = temp;
}
Here's the rest of GroceryList.cpp
#include <iostream>
#include <cstddef>
#include <string>
#include "GroceryList.h"
using namespace std;
using namespace CS151GroceryList;
GroceryList::GroceryList() : top(NULL)
{
//left blank intentionally
}
GroceryList::~GroceryList()
{
while (!empty())
{
/*remove();*/
delete top;
}
}
bool GroceryList::empty()
{
return(top == NULL);
}
void GroceryList::print()
{
ListNode*temp = top;
while (temp != top)
{
cout << temp->item << endl;
temp = temp->link;
}
cout << temp->item << endl;
}
void GroceryList::remove(const string& an_item)
{
if (empty())
{
cout << "Error: remove was attempted on empty list.\n";
exit(1);
}
}
void GroceryList::insert(const string& an_item)
{
if (top == temp.insert)
{
return;
}
char next;
while (!empty())
{
delete(top);
}
if (an_item.insert == NULL)
{
top = NULL;
return;
}
ListNodePtr temp = new ListNode;
temp->item = an_item;
temp->link = top;
top = temp;
}
bool GroceryList::inList(const string& an_item)
{
ListNodePtr temp;
temp = top;
if (temp == an_item.insert)
{
temp = temp->link;
if (temp != an_item.insert)
{
if (temp->link != temp->link)
{
return 1;
}
}
/*cout << "Item is in list. Failed to insert." << endl;
return 1;*/
}
else
{
cout << "Item is not in list. Inserting." << endl;
return 0;
}
}
This is the error I am getting:
error C3867: 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::insert': function call missing argument list; use '&std::basic_string<char,std::char_traits<char>,std::allocator<char>>::insert' to create a pointer to member
I'm pretty sure it is because I am not using the proper value
You have at least these problems in your code:
1)
void GroceryList::insert(const string& an_item)
{
if (top == temp.insert)
{
return;
}
if temp is local variable, then you can't use it without declaration (and, for best, proper initialization). Besides, "insert" is member function call, you've missed the braces and argument list, like that "temp.insert(smth)"
2)
if (an_item.insert == NULL)
{
top = NULL;
return;
}
the same issue, you should provide arguments to member call insert. But you don't need insert call there, because an_item argument of GroceryList::insert, passed by const reference, so you can use it without NULL checks

How to declare an object<template> in c++

I'm having the hardest time figuring this thing out. The error is in line 58 of main.cpp, I wrote a noticeable comment on line 58.
|58|error: expected primary-expression before ';' token
Main.cpp
#include <iostream>
#include <vector>
#include "LinkedList.h"
using namespace std;
bool eic(const string &str1, const string &str2){
if(str1.length() != str2. length())
return false;
for(int i = 0; i < str1.length(); i++)
if(toupper(str1[i]) != toupper(str2[i])) return false;
return true;
}
vector<string> tokenizer(const string &str, char delim, bool emptyok)
{
vector<string> tokens;
string t;
for(int i = 0; i < str.length(); i++)
{
if (str[i] == delim)
{
if(emptyok || (t.length() != 0))
tokens.push_back(t);
t.clear();
continue;
}
t.push_back(str[i]);
}
if(emptyok || (t.length() != 0)) tokens.push_back(t);
return tokens;
}
int main(){
LinkedList<int> sList;// = LinkedList<int>;
string input;
cout << "Type 'commands' to see the list of commands" << endl;
cin >> input;
vector<string> inputV = tokenizer(input,' ',false);
while(!eic(input,"exit")){
if(eic(input,"commands")){
cout << endl;
cout << "Do not include <> in any commands" << endl;
cout << endl;
cout << "Create <name of list>: Create a new list and names it." << endl;
cout << "Print <name of list>: Prints out the entire list." << endl;
cout << "Add <name of list> <item>: Adds an element to the list." << endl;
cout << "Delete <name of list> <item>: Deletes an element from the list." << endl;
cout << "DeleteAll <name of list> <item>: Deletes all occurences of the element from the list." << endl;
cout << "MakeEmpty <name of list>: Removes all elements from the list." << endl;
cout << "Length <name of list>: Tells you how many elements are in the list" << endl;
cout << "Remove <name of list> deletes an entire list" << endl;
cout << "Exit: Terminates the program" << endl;
}
else if(eic(inputV[0],"create")){
sList = LinkedList<int>; // LINE 58 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
sList.setName(inputV[1]);
cout << sList.getName();
//cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"print")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"add")){
//sList->insertItem(9);
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"delete")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"deleteAll")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"makeEmpty")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"length")){
cout << "This function is still under construction" << endl;
}
else if(eic(inputV[0],"remove")){
cout << "This function is still under construction" << endl;
}
else cout << endl << "Invalid inquiry, please enter 'commands' to see a list of valid commands." << endl;
cin >> input;
}
}
If you need it here is my LinkedList.cpp file
#include <iostream>
#include "LinkedList.h"
using namespace std;
template <class xtype>
LinkedList<xtype>::LinkedList()
{
cout << "List created successfuly\n";
}
template <class xtype>
void LinkedList<xtype>::setLength(int x){
length = x;
}
template <class xtype>
int LinkedList<xtype>::getLength(){
return length;
}
template <class xtype>
void LinkedList<xtype>::setName(string x){
name = x;
}
template <class xtype>
string LinkedList<xtype>::getName(){
return name;
}
template <class xtype>
void LinkedList<xtype>::insertItem(xtype item){
node<xtype> *temp = new node<xtype>;
if(head == NULL || head->info > item){
temp->next = head;
head = temp;
}
else{
node<xtype> *q = head;
node<xtype> *p = head->next;
while(p != head && p->info <= item){
q = p;
p = p->next;
}
q->next = temp;
temp->next = p;
}
}
template class LinkedList<int>;
And the LinkedList header file
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
using namespace std;
template <class xtype>
struct node{
xtype info;
node *next;
node *prev;
};
template <class xtype>
class LinkedList
{
public:
LinkedList();
int getLength();
void setLength(int);
void setName(string);
string getName();
//bool searchItem(xtype item);
void insertItem(xtype item);
//void deleteItem(xtype item);
//int numOccur(xtype item);
protected:
private:
node<xtype> *head;
node<xtype> *term;
int length;
string name;
};
#endif // LINKEDLIST_H
Any help you can give me would be much appreciated. I'm brand new to c++, coming from java, and I've just been slaving over this all of last night up until now.
When you declare sList as LinkedList<int>, you already have invoked the default constructor to initialize sList. There's no need to assign this explicitly, as you (try to) do in the failing line.
This demonstrates a confusing but vital concept when coming from Java to C++ : RAII