C++ Iterating through a linked list - c++

So in my current program I am tasked to store a vector of branches. These branches contain a string name, and a pointer to a node.
These nodes store a book, which has an author name, a title, and the number of copies.
Overall, this should create the data structure of a linked list.
Currently I am attempting to write a program to print all the books within a branch.
After adding these books to the branch Alex.
Stan Moon
Bill Sun
Chris Ground
I attempt to print them all out using the printall() function. However, I simply get blank output. Is there something I am missing?
Thanks in advance!
#include "Library.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int total;
int index;
Library::Library()
{
}
struct Node //Has everything in it
{
string author;
string title;
int copies;
Node* next;
};
struct Branch // Stores just the branch, and a point to the node with information in it.
{
string b_name;
Node* next;
};
vector<Branch> lib;
void Library::start()
{
int choice;
cout << "Please select a choice." << endl;
cout << " " << endl;
cout << "1. Create a branch and insert its books" << endl;
cout << "2. Given an author name, a title and a branch name, CHECKOUT that book from the branch." << endl;
cout << "3. Given an author name, title and a branch name, RETURN that book to the branch." << endl;
cout << "4. Given an author name, title and branch name, FIND the number of copies of that book are available in that branch." << endl;
cout << "5. PRINT all books contained in a branch." << endl;
cout << "6. Exit the program." << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 5)
{
printAll();
}
}
void Library::insert()
{
string br;
string auth;
string titl;
cout << "What is the name of the branch?" << endl;
cin >> br;
Branch *branch = new Branch();
branch->b_name = br;
lib.push_back(*branch);
if (total == 0)
{
cout << "What is the author and title of the book?" << endl;
cin >> auth >> titl;
Node *book = new Node();
book->author = auth;
book->title = titl;
book->copies++;
book->next = NULL;
branch->next = book;
total++;
}
do
{
cout << "What is the author and title of the book?" << endl;
cin >> auth >> titl;
Node *book = new Node();
book->author = auth;
book->title = titl;
book->copies++;
book->next = branch->next;
branch->next = book;
total++;
} while (auth != "NONE" && titl != "NONE");
start();
}
void Library::checkout()
{
string auth;
string titl;
string bran;
}
void Library::Return()
{
//TODO
}
void Library::find()
{
//TODO
}
void Library::printAll()
{
for (unsigned int i = 0; i < lib.size(); i++)
{
while (lib.at(i).next != NULL)
{
cout << "There are " << lib.at(i).next->copies << "of " << lib.at(i).next->title << "by " << lib.at(i).next->author << "in branch " << lib.at(i).b_name << endl;
lib.at(i).next = lib.at(i).next->next;
}
}
start();
}

I found some problems of your source code:
You should hold pointer in the lib vector, or it will be cloned when push_back
The insert function was wrongly implemented
You should use loop instead of recusive call, it maybe cause stack overflow
Check the modified version:
#include "Library.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int total;
int index;
Library::Library()
{
}
struct Node //Has everything in it
{
string author;
string title;
int copies;
Node* next;
};
struct Branch // Stores just the branch, and a point to the node with information in it.
{
string b_name;
Node* next;
};
vector<Branch*> lib;
void Library::start()
{
int choice = 0;
do
{
cout << "Please select a choice." << endl;
cout << " " << endl;
cout << "1. Create a branch and insert its books" << endl;
cout << "2. Given an author name, a title and a branch name, CHECKOUT that book from the branch." << endl;
cout << "3. Given an author name, title and a branch name, RETURN that book to the branch." << endl;
cout << "4. Given an author name, title and branch name, FIND the number of copies of that book are available in that branch." << endl;
cout << "5. PRINT all books contained in a branch." << endl;
cout << "6. Exit the program." << endl;
cin >> choice;
switch (choice)
{
case 1:
insert();
break;
case 5:
printAll();
break;
// TODO: other choises
}
} while (choice != 6);
}
void Library::insert()
{
string br;
string auth;
string titl;
cout << "What is the name of the branch?" << endl;
cin >> br;
Branch *branch = new Branch();
branch->b_name = br;
lib.push_back(branch);
Node* lastNode = nullptr;
do
{
cout << "What is the author and title of the book?" << endl;
cin >> auth >> titl;
Node *book = new Node();
book->author = auth;
book->title = titl;
book->copies++;
if (lastNode == nullptr) {
branch->next = book;
}
else {
lastNode->next = book;
}
lastNode = book;
} while (auth != "NONE" && titl != "NONE");
}
void Library::checkout()
{
string auth;
string titl;
string bran;
}
void Library::Return()
{
//TODO
}
void Library::find()
{
//TODO
}
void Library::printAll()
{
for (unsigned int i = 0; i < lib.size(); i++)
{
auto* branch = lib[i];
auto* node = branch->next;
while (node)
{
cout << "There are " <<
node->copies << " of " <<
node->title << " by " <<
node->author << " in branch " <<
branch->b_name << endl;
node = node->next;
}
}
}

Related

How to fix an expected } error at the end of input

The program is a Linked List program and everything ran before I had to make some major changes to the program. When debugging the program everything went smooth until the last line of the code which gave this error:
|175|error: expected '}' at end of input|
Just want to see what could be the major problem for the code.
I tried to space out the program individually to see if I missed an input somewhere but I'm not able to find anything wrong.
#include<iostream>
using namespace std;
class node
{
public:
string name,id;
int age;
node *next;
void add();
void takeout();
void look();
void display();
node(string n,string i,int a)
{
name=n;
id=i;
age=a;
next=NULL;
}
};
class Linkedlist{
private:
node *list;
public:
Linkedlist(){
list = NULL;
}
void add() // adds the information for the linked list
{
string s,i;
int a;
cout << "\nEnter the student's information below.\n";
cout << "Student's Name : ";
cin >> s;
cout << "Student's ID : ";
cin >> i;
cout << "Student's Age : ";
cin >> a;
node *t = new node(s,i,a);
//adding front
t->next=list;
list=t;
}
void takeout()
{
string a;
cout << "\nEnter the Student's ID so their info can be removed. \n";
cout << "Student's ID : ";
cin >> a;
node *prev=NULL,*temp=list;
while(temp!=NULL)
{
if(temp->id==a)
{
cout<<"Found.\n";
break;
}
prev=temp;
temp=temp->next;
}
if(temp==NULL)
{
cout<<"\nInformation not found.\n";
}
else if(prev==NULL)
{
cout<<"Delinked1\n";
list=list->next;
}
else
{
cout<<"Delinked2\n";
prev->next=temp->next;
}
}
void look()
{
string a;
cout << "\nEnter Student's ID to search for their information.\n ";
cout << "Student's ID : ";
cin >> a;
node *temp=list;
while(temp!=NULL)
{
if(temp->id==a)
{
//diplyaing result
cout << "\n------------------------------\n";
cout << "Name :" << temp->name << endl;
cout << "ID :" << temp->id << endl;
cout << "Age :" << temp->age << endl;
cout << "\n------------------------------\n";
break;
}
temp=temp->next;
}
if(temp==NULL)
{
cout << "\nInformation on found.\n";
}
}
void display()
{
node *temp=list;
if(temp==NULL)
cout<<"\nLIST IS EMPTY---\n";
while(temp!=NULL)
{
//displaying
cout << "\n------------------------------\n";
cout << "Name :" << temp->name << endl;
cout << "Age :" << temp->age << endl;
cout << "\n------------------------------\n";
temp=temp->next;
}
}
int main()
{
Linkedlist list;
cout << "Student Information (Linked List)\n\n";
while(1)
{
int choice;
cout << "\n1. Add a node." << endl;
cout << "2. Delete a node." << endl;
cout << "3. Search a node." << endl;
cout << "4. Display a node." << endl;
cout << "Enter your choice : ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
{
list.add();
break;
}
case 2:
{
list.takeout();
break;
}
case 3:
{
list.look();
break;
}
case 4:
{
list.display();
break;
}
default:
cout << "Wrong choice!" << endl;
break;
}
}
}
I know what the code is suppose to show at the end because I ran it before I had to change the inputs but now with this error the program wouldn't run.
class Linkedlist{
private:
node *list;
public:
Linkedlist(){
list = NULL;
}
Oops.... No closing '}'
Though not a requirement by any means, I always found providing consistent formatting with a space between the expression and opening brace helpful to my ability to quickly scan a file and confirm brace balance, e.g.
class Linkedlist {
private:
node *list;
public:
Linkedlist() {
list = NULL;
}
...
}; /* <== this is the missing closing-brace in your code */
And, actually, what has occurred in your case is you are missing the closing brace for the class that includes all member functions below, e.g.
class Linkedlist {
private:
node *list;
public:
Linkedlist() {
list = NULL;
}
void add() // adds the information for the linked list
{
...
void display()
{
node *temp=list;
if(temp==NULL)
cout<<"\nLIST IS EMPTY---\n";
while(temp!=NULL)
{
//displaying
cout << "\n------------------------------\n";
cout << "Name :" << temp->name << endl;
cout << "Age :" << temp->age << endl;
cout << "\n------------------------------\n";
temp=temp->next;
}
}
}; /* <== this is the actual missing closing-brace in your code */
Consistent indenting would help identify that problem. Your code compiles just find after adding the closing '}'.
An addition to your menu would be nice as well:
1. Add a node.
2. Delete a node.
3. Search a node.
4. Display a node.
5. Exit. // exit would be nice
Enter your choice :

C++ Printing Values In Vector Based Binary Tree After Insertion

I am tasked with storing a binary tree within a vector. Within each node is stored an int ID, int Age, and a string name.
The nodes are stored and organized within the vector by ID.
When storing the binary tree within a vector, I am using the algorithm 2i and 2i+1 to dictate a node's left and right child respectively.
I have managed to create an insert method that I believe satisfies these conditions, however for some reason, when attempting to print the values of my vector, I appear to get negative values. For this particular example, I insert the following values
50 21 Tim
75 22 Steve
30 40 Eric
20 35 Mary
100 60 Judy
After inserting these four values, I attempt to use my find() method to find Eric, in which my program returns "Not Found!"
I run my report() function to find that all the values stored within my vector are large negative valued IDs.
Is there a particular reason for this? Find()
Report()
Here is my code.
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int index = 0;
struct Node
{
int ID;
int age;
string name;
Node()
{
}
Node(int id, int Age, string nm)
{
this->ID = id;
this->age = Age;
this->name = nm;
}
};
vector<Node> binaryTree(30);
BST::BST()
{
}
void BST::start()
{
int choice;
cout << "What would you like to do?" << endl;
cout << "1. Add a node to the tree" << endl;
cout << "2. Delete a node from the tree" << endl;
cout << "3. Find a node in the tree" << endl;
cout << "4. Report the contents of the tree" << endl;
cout << "5. Exit program" << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 2)
{
Delete();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
int root = 1;
bool success = false;
cout << "Please enter the ID number, age and name:" << endl;
do
{
cin >> ID >> AGE >> NAME;
} while (ID < 0);
Node *tree = new Node(ID, AGE, NAME);
if (index = 0)
{
binaryTree[1] = *tree;
}
if (index > 0)
{
do
{
if (tree->ID > binaryTree.at(root).ID)
{
root = 2 * root + 1;
}
if (tree->ID < binaryTree.at(root).ID)
{
root = 2 * root;
}
if (binaryTree.at(root).ID == NULL)
{
binaryTree.at(root) = *tree;
success = true;
}
} while (!success);
}
index++;
delete tree;
start();
}
void BST::Delete()
{
int input_id;
cout << "What is the ID of the person to be deleted" << endl;
cin >> input_id;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (input_id == binaryTree.at(i).ID)
binaryTree.erase(binaryTree.begin() + i);
}
cout << " " << endl;
start();
}
void BST::find()
{
int key;
bool found = 0;
cout << "What's the ID?" << endl;
cout << " " << endl;
cin >> key;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (binaryTree.at(i).ID == key)
{
cout << "The ID is " << binaryTree.at(i).ID << endl;
cout << "The age ID " << binaryTree.at(i).age << endl;
cout << "The name is " <<binaryTree.at(i).name << endl;
cout << " " << endl;
found = true;
}
if (found == false)
{
cout << "Not found." << endl;
cout << "" << endl;
break;
}
}
start();
}
void BST::report()
{
cout << "The contents of the tree are" << endl;
cout << " " << endl;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
int level = 0;
if (i == 0) level = 0;
if (i == 1 || i == 2) level = 1;
if (i >= 3 && i <= 6) level = 2;
if (i >= 7 && i <= 14) level = 3;
//TODO complete list
cout << binaryTree.at(i).ID << " " << binaryTree.at(i).age << " " << &binaryTree.at(i).name << " " << level << endl;
}
}
Would appreciate the suggestions/help!
Thanks!
I think issues is with indexing here
In insert() you created binary tree with root at index in but in report() function you started output from index 0. I have no idea what binaryTree.at(int) do.
But in find() your error is due to the fact that you have included if(found == 0) inside the loop. This means that it will break the loop if 1st element of tree is not the element you are searching. Use this code instead
void BST::find()
{
int key;
bool found = 0;
cout << "What's the ID?" << endl;
cout << " " << endl;
cin >> key;
for (unsigned int i = 0; i < binaryTree.size(); i++)
{
if (binaryTree.at(i).ID == key)
{
cout << "The ID is " << binaryTree.at(i).ID << endl;
cout << "The age ID " << binaryTree.at(i).age << endl;
cout << "The name is " <<binaryTree.at(i).name << endl;
cout << " " << endl;
found = true;
}
}
if (found == false)
{
cout << "Not found." << endl;
cout << "" << endl;
}
start();
}

C++ Virtual Void

Okay, so I have a parent class called employee and 3 subclass called manager,researcher and engineer. I made a vector and want to list them. this is the how I process the making.
vector <Employee*,Manager*> EmployeeDB;
Employee *temp;
temp = new Manager(first, last, salary, meetings, vacations);
EmployeeDB.push_back(temp);
I have no problem in making the vector, my concern is listing the info. all 3 subclasses have firstname, lastname and salary but they're difference is that they have different data members which is unique, example the Manager has the int value vacation and the Engineer has the int value experience so on and so forth.
Employee.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef EMPLOYEE_h
#define EMPLOYEE_h
class Employee
{
public:
Employee();
Employee(string firstname, string lastname, int salary);
string getFname();
string getLname();
int getSalary();
virtual void getInfo();
private:
string mFirstName;
string mLastName;
int mSalary;
};
#endif
Employee.cpp:
#include "Employee.h"
#include <iostream>
#include <string>
using namespace std;
Employee::Employee()
{
mFirstName = "";
mLastName = "";
mSalary = 0;
}
Employee::Employee(string firstname, string lastname, int salary)
{
mFirstName = firstname;
mLastName = lastname;
mSalary = salary;
}
string Employee::getFname()
{
return mFirstName;
}
string Employee::getLname()
{
return mLastName;
}
int Employee::getSalary()
{
return mSalary;
}
void Employee::getInfo()
{
cout << "Employee First Name: " << mFirstName << endl;
cout << "Employee Last Name: " << mLastName << endl;
cout << "Employee Salary: " << mSalary << endl;
}
Main:
#include <vector>
#include <iostream>
#include <string>
#include "Employee.h"
#include "Engineer.h"
#include "Manager.h"
#include "Researcher.h"
using namespace std;
vector <Employee*> EmployeeDB;
Employee *temp;
void add()
{
int emp, salary, vacations, meetings, exp, c;
string first, last, type, school, topic;
bool skills;
do
{
system("cls");
cout << "===========================================" << endl;
cout << " Add Employee " << endl;
cout << "===========================================" << endl;
cout << "[1] Manager." << endl;
cout << "[2] Engineer." << endl;
cout << "[3] Researcher." << endl;
cout << "Input choice: ";
cin >> emp;
system("cls");
} while (emp <= 0 || emp > 3);
cout << "===========================================" << endl;
cout << " Employee Info " << endl;
cout << "===========================================" << endl;
cout << "Employee First name: ";
cin >> first;
cout << "Employee Last name: ";
cin >> last;
cout << "Employee Salary: ";
cin >> salary;
switch (emp)
{
case 1:
cout << "Employee numbers of meetings: ";
cin >> meetings;
cout << "Employee numbers of vacations: ";
cin >> vacations;
temp = new Manager(first, last, salary, meetings,vacations);
EmployeeDB.push_back(temp);
delete temp;
break;
case 2:
cout << endl;
cout << "[1]YES [2]NO" << endl;
cout << "Employee C++ Skills: ";
cin >> c;
if (c == 1)
{
skills = true;
}
else
{
skills = false;
}
cout << "Employee Years of exp: ";
cin >> exp;
cout << "(e.g., Mechanical, Electric, Software.)" << endl;
cout << "Employee Engineer type: ";
cin >> type;
temp = new Engineer(first, last, salary, skills, exp, type);
EmployeeDB.push_back(temp);
delete temp;
break;
case 3:
cout << "Employee School where he/she got his/her PhD: ";
cin >> school;
cout << "Employee Thesis Topic: ";
cin >> topic;
temp = new Researcher(first, last, salary, school, topic);
EmployeeDB.push_back(temp);
delete temp;
break;
}
}
void del()
{
}
void view()
{
for (int x = 0; x < (EmployeeDB.size()); x++)
{
cout << EmployeeDB[x]->getInfo();
}
}
void startup()
{
cout << "===========================================" << endl;
cout << " Employee Database " << endl;
cout << "===========================================" << endl;
cout << "[1] Add Employee." << endl;
cout << "[2] Delete Employee." << endl;
cout << "[3] List Employees." << endl;
cout << "[4] Exit." << endl;
cout << "Please Enter Your Choice: ";
}
int main(int argc, char** argv)
{
bool flag = true;
int choice;
do {
do
{
system("cls");
system("pause>nul");
startup();
cin >> choice;
} while (choice < 0 || choice >4);
switch (choice)
{
case 1:
add();
break;
case 2:
del();
break;
case 3:
view();
break;
case 4:
flag = false;
system("EXIT");
break;
}
} while (flag == true);
return 0;
system("pause>nul");
}
I am getting error on the view() function.
It says no operator<< matches these operands
binary '<<': no operator found which takes a right hand operand of type void etc etc.
The problem is that the getInfo has return type void and you are trying to put that return value into cout.
It's important to understand that the code std::cout << val actually calls the function operator<<(ostream& out, const objectType& val) where objectType is the type of 'val'.
In your case the type is void, and there is simply no implementation of operator<< that takes void as a type. hence the error "no operator found which takes a right hand operand of type void...".
In order to fix your issue you have a few options:
Change view() to be
for (...)
{
EmployeeDB[x]->getInfo();
}
Change getInfo() to return a string the info as you'd like:
std::string getInfo()
{
std::string info;
info =...
return info;
}
Create an operator<< for Employee and change view to call it:
view()
{
for (...)
{
std::cout << EmployeeDB[x];
}
}

Extra output during display listnode in c++

For some odd reason when I attempt to display the range of my list it is giving extra output. The program asks for the user to enter the start and end node integers to display and then for some reason it will display a blank node and then the first node. After about 10 seconds it will then display the correct range of nodes.
for instance, i would input
ball, 4, 9.99
doll, 2, 10.00
lava lamp, 5, 24.99
but when putting say a range of 2 to 3 it would output
2. (blank), (blank), (blank)
3. ball, 4, 9.99
(pause for 10 seconds that is not called for)
2. doll, 2, 10.00
3. lava lamp, 5, 24.99
Does anyone know why this may be? (The function in question is void displayRange)
#include <iostream>
#define nullptr 0
#include <cstdlib>
#include <algorithm>
#include <string>
#include <conio.h>
using namespace std;
int menu();
class ItemList {
private:
struct ListNode{
string IName;
string QQuantity;
string PPrice;
double value;
struct ListNode * next;
};
ListNode *head;
public:
ItemList()
{
head = new ListNode;
head->next=nullptr;
}
~ItemList();
void insertNode(string Item, string Quantity, string Price)
{
ListNode *newNode;
ListNode *nodePtr;
ListNode *previousNode=nullptr;
newNode=new ListNode;
newNode->IName=Item;
newNode->QQuantity=Quantity;
newNode->PPrice=Price;
if(!head)
{
head=newNode;
newNode->next=nullptr;
}
else
{
nodePtr=head;
previousNode=nullptr;
while(nodePtr != nullptr && nodePtr->IName < Item)
{
previousNode=nodePtr;
nodePtr=nodePtr->next;
}
if(previousNode==nullptr)
{
head=newNode;
newNode->next=nodePtr;
}
else
{
previousNode->next=newNode;
newNode->next=nodePtr;
}
}
}
void displayNode()
{
ListNode *nodePtr;
nodePtr=head->next;
int i=0;
while(nodePtr)
{
i++;
cout << i << ". " << nodePtr->IName << ", ";
cout << nodePtr->QQuantity << " ";
cout << "$" << nodePtr->PPrice << "\n" << endl;
nodePtr=nodePtr->next;
}
if(!head)
{
cout << "The store is empty." << endl;
}
}
void modifyNode(string Item)
{
ListNode *nodePtr;
ListNode *nodePrev;
string newName, newQuantity, newPrice;
int modify;
if (!head)
{
return;
cout << "Store is empty." << endl;
}
else
{
nodePtr = head;
if (head->IName==Item)
nodePtr = head->next;
else
{
while (nodePtr != nullptr && nodePtr->IName != Item)
{
nodePrev = nodePtr;
nodePtr = nodePtr->next;
}
}
if (nodePtr)
{
cout << nodePtr->IName << "\t" << nodePtr->QQuantity << "\t" << nodePtr->PPrice << endl;
cout << "What would you like to change?\n";
cout << "1. Item" << endl;
cout << "2. Quantity" << endl;
cout << "3. Price" << endl;
cout << "4. Whole Entry" << endl;
cin >> modify;
switch (modify)
{
case 1:
cout << "Change to what?\n";
cin.sync();
getline(cin,newName);
transform(newName.begin(), newName.end(), newName.begin(), ::toupper);
nodePtr->IName = newName;
break;
case 2:
cout << "Change to what?\n";
cin >> newQuantity;
transform(newQuantity.begin(), newQuantity.end(), newQuantity.begin(), ::toupper);
nodePtr->QQuantity = newQuantity;
break;
case 3:
cout << "Change to what?\n";
cin >> newPrice;
transform(newPrice.begin(), newPrice.end(), newPrice.begin(), ::toupper);
nodePtr->PPrice = newPrice;
break;
case 4:
cout << "What is the product called?\n";
cin.sync();
getline(cin,newName);
transform(newName.begin(), newName.end(), newName.begin(), ::toupper);
nodePtr->IName = newName;
cout << "How many are there really?\n";
cin >> newQuantity;
transform(newQuantity.begin(), newQuantity.end(), newQuantity.begin(), ::toupper);
nodePtr->QQuantity = newQuantity;
cout << "What is the actual price?\n";
cin >> newPrice;
transform(newPrice.begin(), newPrice.end(), newPrice.begin(), ::toupper);
nodePtr->PPrice = newPrice;
}
}
else
cout << "Product not found\n";
}
}
void deleteNode(string Item)
{
ListNode *nodePtr;
ListNode *previousNode;
if(!head)
return;
if(head->IName==Item)
{
nodePtr=head->next;
delete head;
head=nodePtr;
}
else
{
nodePtr=head;
while(nodePtr!=nullptr && nodePtr->IName!=Item)
{
previousNode=nodePtr;
nodePtr=nodePtr->next;
}
if(nodePtr)
{
previousNode->next=nodePtr->next;
delete nodePtr;
}
else
{
cout << "Nothing to delete." << endl;
}
}
}
void deleteRangeNode(int start, int stop)
{
ListNode *nodePtr;
ListNode *newNode;
nodePtr = head;
int i=-1;
cin.sync();
while(nodePtr!=nullptr)
{
i++;
if((i>=start)&&(i<=stop))
{
newNode->next = nodePtr -> next;
cout << "Deleted Product: " << nodePtr->IName << endl;
delete nodePtr;
nodePtr=newNode;
}
newNode=nodePtr;
nodePtr=nodePtr->next;
}
}
void displayRange(int start, int stop)
{
ListNode * nodePtr;
nodePtr=head;
int i=-1;
bool found=false;
cin.sync();
while(nodePtr!=nullptr)
{
i++;
if((i>=start && i<=stop))
{
cout << i << ". " << nodePtr->IName << ", ";
cout << nodePtr->QQuantity << " ";
cout << "$" << nodePtr->PPrice << "\n" << endl;
nodePtr=nodePtr->next;
}
}
}
};
ItemList::~ItemList()
{
ListNode *nodePtr;
ListNode *nextNode;
nodePtr=head;
while(nodePtr!=nullptr)
{
nextNode=nodePtr->next;
delete nodePtr;
nodePtr=nextNode;
}
}
int main()
{
ItemList pro;
int method;
while(method!=0)
{
int method=menu();
system("cls");
string It, Q, P;
int begin, end;
switch(method)
{
case 1:
int count;
cout << "How many products would you like to put in?" << endl;
cin >> count;
system("cls");
for(int i=0; i<count; i++)
{
cout << "Product #" << i + 1 << endl;
cout << "Enter the item name: ";
cin.sync();
getline(cin,It);
transform(It.begin(), It.end(), It.begin(), ::toupper);
cout << "Enter the Quantity: ";
cin >> Q;
transform(Q.begin(), Q.end(), Q.begin(), ::toupper);
cout << "Enter the Price: ";
cin >> P;
pro.insertNode(It, Q, P);
cout << "\n";
}
break;
case 2:
int dis;
cout << "How many products would you like to display?" << endl;
cout << "1. Entire Store" << endl;
cout << "2. Range of Products" << endl;
cin >> dis;
system("cls");
switch(dis)
{
case 1:
pro.displayNode();
break;
case 2:
cout << "The display should START at: ";
cin >> begin;
cout << "The display should END at: ";
cin >> end;
pro.displayRange(begin,end);
system("pause");
break;
}
break;
case 3:
pro.displayNode();
cout << "What product do you wish to modify? (by item name)" << endl;
cin.sync();
getline(cin, It);
transform(It.begin(), It.end(), It.begin(), ::toupper);
system("cls");
pro.modifyNode(It);
break;
case 4:
int del;
cout << "Do you wish to delete one product or more?" << endl;
cout << "1. One" << endl;
cout << "2. Range of Products" << endl;
cout << "3. Entire Store" << endl;
cin >> del;
system("cls");
switch(del)
{
case 1:
cout << "What product do you wish to delete? (by item name)" << endl;
pro.displayNode();
cout << "\n";
cin.sync();
getline(cin,It);
transform(It.begin(), It.end(), It.begin(), ::toupper);
pro.deleteNode(It);
cout << "\n";
break;
case 2:
pro.displayNode();
cout << "What range of items do you wish to delete?" << endl;
cout << "START: ";
cin >> begin;
cout << "STOP: ";
cin >> end;
pro.deleteRangeNode(begin, end);
break;
case 3:
pro.~ItemList();
cout << "All items deleted." << endl;
break;
}
break;
case 0:
cout << "Exiting the program." << endl;
return 0;
}
system("pause");
system("cls");
}
return 0;
}
int menu()
{
string space1= " ";
string space2= " ";
int method;
cout << space1 << "What would you like to do to the store?" << endl;
cout << space2 << "1. Add Product" << endl;
cout << space2 << "2. Display" << endl;
cout << space2 << "3. Modify Product" << endl;
cout << space2 << "4. Delete Product" << endl;
cout << space2 << "0. Exit\n" << endl;
cout << space2;
cin >> method;
return(method);
}
The root of your problem is that you are creating a sentinel node in the list, but then not ignoring it in displayRange. You are ignoring it when you call displayNode. The reason you are seeing the delay is because the loop in displayNode relies on signed integer overflow (which is undefined behavior) to terminate. Moving the increment of nodePtr outside of the range check will fix this.
There are several problems with this code. There are many reasons not to implement your own list container, but the most important one is because it's hard to get exactly correct the first time unless you are experienced with the language. I strongly encourage you to look into std::vector. Here is a list of items I found.
#define nullptr 0 DO NOT DO THIS. The standard does not guarantee that this is well defined behavior, and the two do not have the same type.
Calling cin.sync() isn't guaranteed to do anything (it's implementation defined).
You need to clear the whitespace from the input stream before you try to call std::getline on it. This is covered in the reference page under "Notes."
When inserting a new node, you need to set newNode->next to null.
Turn on your compiler's warnings. You have a several usages of uninitialized variables which can lead to undefined behavior.
Cause of blank node Problem: insertion started at next-node of head in insertNode method. But, display started from head in displayRange method.
Solution: Resolve this mismatch !!! You can resolve this problem by changing ItemList as followings:
ItemList()
{
head = nullptr; //changed here
}
Cause of wrong range and late display Problems: display pointer (nodePtr) is not updated accordingly.
Solution: Resolve this mismatch !!! You can resolve this problem by changing displayRange as followings:
void displayRange(int start, int stop)
{
ListNode * nodePtr;
nodePtr = head;
int i = 0; //changed here
bool found = false;
cin.sync();
while (nodePtr != nullptr)
{
i++;
if ((i >= start && i <= stop))
{
cout << i << ". " << nodePtr->IName << ", ";
cout << nodePtr->QQuantity << " ";
cout << "$" << nodePtr->PPrice << "\n" << endl;
//nodePtr = nodePtr->next; //changed here
}
nodePtr = nodePtr->next; //changed here
}
}
I just pointed out the mention problems area, though it has some other bugs.
Thanks !!!

How can I append more nodes in this doubly linked list by using my pointers and structures?

I'm not getting any errors, but I am not able to append songs to the doubly linked list.`I do not currently have any delete operators because I plan on adding them near the end of creating the program.
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
struct Song
{
int id;
string name;
string singerName;
};
struct Node
{
Song sg;
Node* next;
Node* prev;
};
struct FirstSong
{
Node* first;
};
Node *getLastSong(FirstSong *head);
void addSong(FirstSong *head, Node *tail);
Node *removeSong(FirstSong *head, int index);
void displayListElements(FirstSong *head);
void clearList(FirstSong *head);
int main()
{
Node* tail;
FirstSong* head;
int choice;
int ID;
string name;
string singer;
//Creating the first node
head = new FirstSong;
head->first = new Node;
cout << "What is your song's number" << endl;
cin >> ID;
head->first->sg.id = ID;
cout << "What is the name of your song?" << endl;
cin.ignore();
getline(cin, name);
head->first->sg.name = name.c_str();
cout << "What is the name of your singer?" << endl;
getline(cin, singer);
head->first->sg.singerName = singer.c_str();
head->first->prev = NULL;
tail = head->first;
//Prompting user for what they want to do
cout << "What would you like to do now?" << endl;
labelA:
cout << "1 - add song" << endl;
cout << "2 - remove song" << endl;
cout << "3 - show last song" << endl;
cout << "4 - display all songs" << endl;
cout << "5 - clear songs" << endl;
cout << "6 - quit" << endl;
cin >> choice;
//Switch statement will be right here
return 0;
}
Node *getLastSong(FirstSong *head)
{
}
void addSong(FirstSong *head, Node *tail)
{
Node* n;
char choice;
int ID;
string name;
string singer;
myLabelB:
if(tail->next == NULL){
cout << "NULL" << endl;
}
else{
cout << "Not NULL" << endl;
}
n = new Node;
cout << "What is your song's number" << endl;
cin >> ID;
n->sg.id = ID;
cout << "What is the name of your song?" << endl;
cin.ignore();
getline(cin, name);
n->sg.name = name.c_str();
cout << endl;
cout << "What is the name of your singer?" << endl;
getline(cin, singer);
n->sg.singerName = singer.c_str();
n->prev = tail;
tail->next = n;
tail = n;
cout << "Add another song?" << endl;
cin >> choice;
if(choice == 'Y' || choice == 'y')
{
goto myLabelB;
}
else
{
tail->next = NULL;
}
}
Node *removeSong(FirstSong *head, int index)
{
}
void displayListElements(FirstSong *head)
{
Node* temp = head->first;
while(temp != NULL){
cout << temp->sg.id << " ";
cout << temp->sg.name << " ";
cout << temp->sg.singerName << " " << endl;
temp = temp->next;
cout << endl;
}
}
What can I do to append the new songs without deleting the old ones? My guess is that I am somehow setting the newest Node = NULL, but I can't find where.