overloaded << insertion operator isn't working correctly - c++

So I can't figure out why my insertion operator isn't working for my list class. I've looked at it for a while and I think the syntax is correct for overloading. Not sure on this one. Any hints as to why it's not working?? Here's the code:
EDIT:Changed some code around to what it currently is right now.
Sorry, the problem specifically now is that I cannot get it to print anything out, it simple prints and empty line.
here's the driver:
#include <iostream>
#include "polynomial.h"
using namespace std;
int main(){
Polynomial* poly = new Polynomial();
poly->set_coefficient(3,2);
poly->set_coefficient(0,2);
poly->set_coefficient(3,1);
cout << "trying to print data" << endl;
cout << *poly << endl;
return 0;
}
Here's the header:
#ifndef _POLYNOMIAL_H_
#define _POLYNOMIAL_H_
#include <iostream>
class Polynomial {
public:
struct PolyNode {
int coefficient, degree;
struct PolyNode* next;
PolyNode(int c, int d, PolyNode* n): coefficient(c),degree(d),next(n){}
};
PolyNode* firstTerm;
Polynomial(): firstTerm(0) {}
struct PolyNode* get_first(){
return firstTerm;
}
//makes the term with degree d have a coefficient of c
void set_coefficient(int c, int d);
~Polynomial();
friend std::ostream& operator<<(std::ostream& o, const Polynomial& p);
};
#endif
Here's the implementation:
#include "polynomial.h"
#include <iostream>
#include <ostream>
using namespace std;
void Polynomial::set_coefficient(int c, int d){
PolyNode* start = firstTerm;
if(c != 0 && firstTerm == 0)
firstTerm = new PolyNode(c,d,NULL);
else{
cout << "Entered set_coefficient()" << endl;
while(start->degree != d && start->next != NULL){
cout << "Inside set_coefficient() while loop" << endl;
start = start->next;
}
if(c != 0 && start == 0)
start = new PolyNode(c,d,0);
else if(c!= 0 && start != 0)
start->coefficient = c;
else if(c == 0){
cout << "deleting a term" << endl;
delete start;
}
}
cout << "Leaving set_coefficient()" << endl;
}
ostream& operator<<(ostream& o,const Polynomial& p){
Polynomial::PolyNode* start = p.firstTerm;
for(unsigned int i = 0; start->next != 0; i++){
o << "Term " << i << "'s coefficient is: " << start->coefficient << " degree is: " << start->degree << endl << flush;
start = start->next;
}
return o;
}

poly is a pointer, to use your custom operator << you need to say
cout << *poly; // output the object pointed-to, not the pointer itself
You haven't overloaded what it means to insert a Polynomial*. Nor should you try.
Besides that, you probably should accept the object by const reference, there's no reason for a stream output operator to go changing the object.

Related

AVLTree can't find data when searched for

I am working on an assignment for school. I have to create an AVLTree, read data from a text file and then create Professor object with that data. However, when I try and search for a Professor by name, it can't be found. It keeps defaulting to Michael Scott in the program and can't find who I'm looking for. My readFromFile function works perfectly and gets me all the data from the file, so I have the data. At this point it's a matter of issues with the AVL Tree. I'll link everything below.
Driver.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "AVLTree.h"
using namespace std;
void readFromFile(AVLTree *treeAccess) {
int numOfProfs = 0;
string line;
const char *path="/Users/collinchappell/Desktop/Program4Official/Program4Official/ProfessorData.txt";
fstream myFile (path, ios::in);
if (!myFile) {
cout << "Sorry can't read ProfessorData.txt!" << endl;
}
else {
// Splitting up all the data in the .txt file and the looping through using string stream
// Not the best solution, however nothing else would work for me so this is what I went with.
while (getline(myFile, line)) {
string n;
string nT;
string s;
int b1,b2,b3,b4,b5,b6,b7;
replace(line.begin(), line.end(), '$', ' ');
stringstream ss(line);
for (int k = 0; k < 11; k++) {
ss >> n;
ss >> nT;
n = n + " " + nT;
ss >> s;
ss >> b1;
ss >> b2;
ss >> b3;
ss >> b4;
ss >> b5;
ss >> b6;
ss >> b7;
numOfProfs++;
Professor p(n, s, b1, b2, b3, b4, b5, b6, b7);
cout << p;
treeAccess->insertNode(n, &p);
}
}
}
cout << numOfProfs << " Proffesors have added from the file." << endl << endl;
}
int main() {
AVLTree tree;
readFromFile(&tree);
bool cont = true;
while (cont) {
cout << "Which Computer Science professor do you want details about?" << endl;
tree.displayInOrder();
cout << endl << endl << "Type Professor Name: ";
string typeName;
getline(cin, typeName);
while (tree.searchNode(typeName) == NULL) {
cout << "Couldn't find that professor! Please type another: ";
getline(cin, typeName);
}
cout << tree.searchNode(typeName);
cout << "Would you like to search another? (Y/N): ";
string ans;
cin >> ans;
if (ans == "y" || ans == "Y") {
continue;
}
else if (ans == "n" || ans == "N") {
return 0;
}
}
return 0;
}
AVLTree.h:
#ifndef AVLTree_h
#define AVLTree_h
#include <iostream>
#include "Professor.h"
using namespace std;
class AVLTree {
private:
// TreeNode structure
struct TreeNode {
string name;
Professor *prof;
struct TreeNode* left;
struct TreeNode* right;
};
// Root of tree
TreeNode* root;
// Function declarations
void insert(TreeNode *&nodePtr, TreeNode *&newNode);
void destroySubTree(TreeNode *nodePtr);
void displayInOrder(TreeNode *nodePtr) const;
int height(TreeNode *nodePtr);
int diff(TreeNode *nodePtr);
void balance(TreeNode *&temp);
TreeNode* l_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->right;
parent->right = temp->left;
temp->left = parent;
return temp;
}
TreeNode* r_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
TreeNode* lr_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->left;
parent->left = (l_rotation(temp));
return r_rotation(parent);
}
TreeNode* rl_rotation(TreeNode *parent) {
TreeNode *temp;
temp = parent->right;
parent->right = (r_rotation(temp));
return l_rotation(parent);
}
public:
AVLTree() { // Constructor
root = NULL;
}
~AVLTree() { // Destructor
destroySubTree(root);
}
void insertNode(string n, Professor* professor);
Professor* searchNode(string);
// Call private displayInOrder()
void displayInOrder() const {
displayInOrder(root);
}
};
#endif /* AVLTree_h */
AVLTree.cpp:
#include <iostream>
#include "AVLTree.h"
using namespace std;
// Insert a node into the tree recursively
void AVLTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) {
if (nodePtr == NULL) {
nodePtr = newNode;
}
else if (newNode->name < nodePtr->name) {
insert(nodePtr->left, newNode);
balance(nodePtr);
}
else {
insert(nodePtr->right, newNode);
balance(nodePtr);
}
}
// Destory the sub tree
void AVLTree::destroySubTree(TreeNode *nodePtr) {
if (nodePtr) {
if (nodePtr->left) {
destroySubTree(nodePtr->left);
}
if (nodePtr->right) {
destroySubTree(nodePtr->right);
}
delete nodePtr;
}
}
// Display the tree in order
void AVLTree::displayInOrder(TreeNode *nodePtr) const {
if (nodePtr) {
displayInOrder(nodePtr->left);
cout << nodePtr->name << endl;
displayInOrder(nodePtr->right);
}
}
// Get the tree's height
int AVLTree::height(TreeNode *temp) {
int leftHeight, rightHeight;
if (temp) {
leftHeight = height(temp->left);
rightHeight = height(temp->right);
if (leftHeight > rightHeight) {
return leftHeight + 1;
}
else if (leftHeight < rightHeight) {
return rightHeight + 1;
}
else {
return 0;
}
}
return 0;
}
// Get the difference
int AVLTree::diff(TreeNode *temp) {
int l_height = height(temp->left);
int r_height = height(temp->right);
return l_height - r_height;
}
// Balance the tree
void AVLTree::balance(TreeNode *&temp) {
int bal_factor = diff (temp);
if (bal_factor > 1)
{
if (diff(temp->left) > 0) // 2, 1 RIGHT
{
temp = r_rotation(temp);
cout << "\nRIGHT rotation";
}
else // 2, -1 LEFT-RIGHT
{
temp = lr_rotation(temp);
cout << "\nLEFT-RIGHT rotation";
}
}
else if (bal_factor < -1)
{
if (diff (temp->right) > 0) // -2, 1 RIGHT-LEFT
{
temp = rl_rotation(temp);
cout << "\nRIGHT-LEFT rotation";
}
else // -2, -1 LEFT
{
temp = l_rotation(temp);
cout << "\nLEFT Rotation";
}
}
}
// Insert a node, calls the private insert function
void AVLTree::insertNode(string n, Professor *proffesor) {
TreeNode *newNode = NULL; // Pointer to a new node.
newNode = new TreeNode;
newNode->name = n;
newNode->prof = proffesor;
newNode->left = newNode->right = NULL;
// Insert the node.
insert(root, newNode);
}
Professor* AVLTree::searchNode(string s) {
cout << "Name inputted into search: " << s << endl;
cout << endl << "Actual name: " << root->name << endl;
TreeNode *nodePtr = root;
while (nodePtr != NULL) {
if (nodePtr->name == s) {
return nodePtr->prof;
}
else if (nodePtr->name > s) {
nodePtr = nodePtr->left;
cout << "Left -> " << nodePtr << endl;
}
else {
nodePtr = nodePtr->right;
cout << "Right -> " << nodePtr << endl;
}
}
return NULL;
}
Professor.h:
#ifndef PROFESSOR_H
#define PROFESSOR_H
#include <iostream>
#include <iomanip>
using namespace std;
class Professor
{
private:
string name;
string course;
bool clearGrading;
bool goodFeedback;
bool caring;
bool reachable;
bool toughGrader;
bool lectureHeavy;
bool attendance;
public:
Professor(string n, string course, bool cG, bool gF, bool c, bool r, bool tG, bool lH, bool a) {
this->name = n;
this->course = course;
this->clearGrading = cG;
this->goodFeedback = gF;
this->caring = c;
this->reachable = r;
this->toughGrader = tG;
this->lectureHeavy = lH;
this->attendance = a;
}
friend ostream &operator << (ostream &strm, Professor &p)
{
strm << endl << endl;
strm << setw(30) << "Professor:" << setw(20) << p.name << endl;
strm << setw(30) << "Course:" << setw(20) << p.course << endl;
strm << setw(30) << "Clear Grading Criteria:" << setw(20);
if(p.clearGrading == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Provides Good Feedback:" << setw(20);
if(p.goodFeedback == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Caring:" << setw(20);
if(p.caring == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Reachable Outside of Class:" << setw(20);
if(p.reachable == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Tough Grader:" << setw(20);
if(p.toughGrader == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Lecture Heavy:" << setw(20);
if(p.lectureHeavy == 0) strm << "no"; else strm << "yes";
strm << endl;
strm << setw(30) << "Attendance Mandatory:" << setw(20);
if(p.attendance == 0) strm << "no"; else strm << "yes";
strm << endl;
return strm;
}
};
#endif
ProfessorData.txt:
Michael Scott$CSC1310$0$0$1$1$0$1$1$Jim Halpert$CSC1310$1$1$1$0$0$0$0$Pam Beesly$CSC1300$1$1$1$0$1$0$1$Dwight Schrute$CSC2400$1$1$0$0$1$1$1$Angela Martin$CSC1300$1$0$0$0$1$1$1$Kelly Kapoor$CSC1300$0$0$0$0$0$0$0$Andy Bernard$CSC2400$1$0$1$1$0$1$1$Kevin Malone$CSC1310$0$1$1$1$0$0$0$Meredith Palmer$CSC1310$0$1$1$1$0$0$0$Phyllis Vance$CSC1300$1$1$1$0$1$0$0$Oscar Nunez$2400$1$1$1$1$1$1$1$
Running the program:
11 Proffesors have added from the file.
Which Computer Science professor do you want details about?
Andy Bernard
Angela Martin
Dwight Schrute
Jim Halpert
Kelly Kapoor
Kevin Malone
Meredith Palmer
Michael Scott
Oscar Nunez
Pam Beesly
Phyllis Vance
Type Professor Name: Andy Bernard
Name inputted into search: Andy Bernard
Actual name: Michael Scott
Left -> 0x100704570
Left -> 0x105a045b0
Left -> 0x105b04120
Left -> 0x105b041a0
Name inputted into search: Andy Bernard
Actual name: Michael Scott
Left -> 0x100704570
Left -> 0x105a045b0
Left -> 0x105b04120
Left -> 0x105b041a0
0x7ffeefbfee18Would you like to search another? (Y/N):
As you can see, I've put in some prints to kind of debug what's happening. I believe my objects are not getting inserted into the tree right, or my search function is off. Also, I'm not 100% on the balance function. Any help would be amazing.

class variable getting altered by code that were seemingly not executed

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

"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.

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

<<operator is only printing an empty line

In main the list prints out using the insertion operator, but all that I get is an empty line. Not sure why. Is it that there is nothing being stored in the list even when you use the set_coefficient? Any other critiquing is welcome. Thanks
here's the driver:
#include <iostream>
#include "polynomial.h"
using namespace std;
int main(){
Polynomial* poly = new Polynomial();
poly->set_coefficient(3,2);
poly->set_coefficient(0,2);
poly->set_coefficient(3,1);
cout << "trying to print data" << endl;
cout << *poly << endl;
return 0;
}
Here's the header:
#ifndef _POLYNOMIAL_H_
#define _POLYNOMIAL_H_
#include <iostream>
class Polynomial {
public:
struct PolyNode {
int coefficient, degree;
struct PolyNode* next;
PolyNode(int c, int d, PolyNode* n): coefficient(c),degree(d),next(n){}
};
PolyNode* firstTerm;
Polynomial(): firstTerm(0) {}
struct PolyNode* get_first(){
return firstTerm;
}
//makes the term with degree d have a coefficient of c
void set_coefficient(int c, int d);
~Polynomial();
friend std::ostream& operator<<(std::ostream& o, const Polynomial& p);
};
#endif
Here's the implementation:
#include "polynomial.h"
#include <iostream>
#include <ostream>
using namespace std;
void Polynomial::set_coefficient(int c, int d){
PolyNode* start = firstTerm;
if(c != 0 && firstTerm == 0)
firstTerm = new PolyNode(c,d,NULL);
else{
cout << "Entered set_coefficient()" << endl;
while(start->degree != d && start->next != NULL){
cout << "Inside set_coefficient() while loop" << endl;
start = start->next;
}
if(c != 0 && start == 0)
start = new PolyNode(c,d,0);
else if(c!= 0 && start != 0)
start->coefficient = c;
else if(c == 0){
cout << "deleting a term" << endl;
delete start;
}
}
cout << "Leaving set_coefficient()" << endl;
}
ostream& operator<<(ostream& o,const Polynomial& p){
Polynomial::PolyNode* start = p.firstTerm;
for(unsigned int i = 0; start->next != 0; i++){
o << "Term " << i << "'s coefficient is: " << start->coefficient << " degree is: " << start->degree << endl << flush;
start = start->next;
}
return o;
}
if(c != 0 && start == 0)
start = new PolyNode(c,d,0);
else if(c!= 0 && start != 0)
start->coefficient = c;
else if(c == 0){
cout << "deleting a term" << endl;
delete start;
}
if (c != 0 && start == 0) // this situation may occur ? you have already judged surrounding if
else if (c == 0) {
cout << "deleting a term" << endl;
delete start; // that may be cause linkedList detach.
}
cout << "Entered set_coefficient()" << endl;
while(start->degree != d && start->next != NULL){
cout << "Inside set_coefficient() while loop" << endl;
start = start->next;
}
if(c != 0 && start == 0)
start = new PolyNode(c,d,0);
else if(c!= 0 && start != 0)
start->coefficient = c;
else if(c == 0){
cout << "deleting a term" << endl;
delete start;
}
It appears you want a linked list, but you're neither creating nor removing links (start->next), only allocating memory. Without setting up the links, there is no list.
There are probably multiple bugs here :>
ostream& operator<<(ostream& o,const Polynomial& p){
Polynomial::PolyNode* start = p.firstTerm;
for(unsigned int i = 0; start->next != 0; i++){
this won't print the last PolyNode...