I need to create a doubly linked list that stores different types of data.
I can’t enter a few words through the console through space in one line so that they are written in one variable. I tried to use cin.getline(book.plant, 50); but it doesn`t work correctly.
And I cannot make a delete function. I want to make a function that deletes the line in which the first element is equal to the one I enter. Each time I run the code, it displays to me: there is no such element.
Here is my code:
#include <iostream>
#include <list>
#include <locale>
#include <cstdlib>
#include <stdlib.h>
#include <list>
using namespace std;
typedef struct // создание узла двусвязного списка
{
char plant[50];
char family[50];
char species[50]; //вид
char sort[50]; //род
char purpose[50]; //призначення
char territory[50]; //територія зростання
//char map[50]; // карта обліку
char compatibility[50]; //сумістність зіншими видами
}BOOK;
typedef struct tag_obj
{
BOOK b;
struct tag_obj* prev, * next;
}OBJ;
OBJ* head = NULL, * tail = NULL;
void add_obj(OBJ* obj, BOOK book) {
OBJ* ptr = new OBJ;
ptr->b = book;
ptr->prev = obj;
ptr->next = (obj == NULL) ? NULL : obj->next;
if (obj != NULL) {
obj->next = ptr;
if (obj->next != NULL) obj->next->prev = ptr;
}
if (ptr->prev == NULL) head = ptr;
if (ptr->next == NULL) tail = ptr;
}
void del_obj(OBJ* obj) {
char x[50];
cout << "enter the name of the plant whose data you want to delete: ";
cin >> x;
OBJ* tmp;
OBJ* h;
if (head == NULL) // емли нет не одного узла, то возращаемся
{
cout << "List empty,nothing to delete" << endl;
return;
}
if (head->b.plant == x) //удаляем первый елемент
{
tmp = head;
head = head->next; // теперь голова -это следующий елемент
head->prev = NULL; // предыдущего не существует
cout << "Element Deleted" << endl;
free(tmp);
return;
}
h = head;
while (h->next->next != NULL)
{
if (h->next->b.plant == x) // удаляем елемент после
{
tmp = h->next;
h->next = tmp->next;
tmp->next->prev = h;
cout << "Element Deleted" << endl;
free(tmp);
return;
}
h = h->next;
}
if (h->next->b.plant == x) // удаление последнего елемента
{
tmp = h->next;
free(tmp);
h->next = NULL; //следующего не существует
cout << "Element Deleted" << endl;
return;
}
cout << "Element " << x << " not found" << endl;
}
void show() {
OBJ* c = head;
while (c != NULL) {
cout << c->b.plant << " " << c->b.family << " " << c->b.species << " " << c->b.sort << " " << c->b.purpose << " " << c->b.territory << " " << c->b.compatibility << endl ;
c = c->next;
}
}
int main() {
//setlocale(LC_ALL, "ukr");
BOOK book = { " PLANT "," FAMILY " };
//add_obj(tail, book);
int choice;
char x;
cout << "**plant account**" << endl;
cout << "1(add an element to the beginning)" << endl;
cout << "2(add an element to the end)" << endl;
cout << "3(delete)" << endl;
cout << "4(show)" << endl;
cout << "6(exit)" << endl << endl;
while (222)
{
cout << " Choose action : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Plant name: ";
cin >> book.plant;
cout << "Plant family: ";
cin >> book.family;
cout << "Plant species: ";
cin >> book.species;
cout << "Plant sort: ";
cin >> book.sort;
cout << "Purpose of the plant: ";
cin >> book.purpose;
cout << "Growth area: ";
cin >> book.territory;
cout << "Compatibility with other species: ";
cin >> book.compatibility;
add_obj(head, book);
cout << endl;
break;
case 2:
cout << "Plant name: ";
cin >> book.plant;
cout << "Plant family: ";
cin >> book.family;
cout << "Plant species: ";
cin >> book.species;
cout << "Plant sort: ";
cin >> book.sort;
cout << "Purpose of the plant: ";
cin >> book.purpose;
cout << "Growth area: ";
cin >> book.territory;
cout << "Compatibility with other species: ";
cin >> book.compatibility;
add_obj(tail, book);
cout << endl;
break;
case 3:
del_obj(head);
cout << endl;
break;
case 4:
show();
cout << endl;
break;
case 5:
cout << " " << endl;
exit(222);
}
}
return 0;
}
Related
I am using Code::Blocks to write this C++ program, but everytime I do a 3rd Insert on the Link List, and when I use the Display option to check my work, I get a strange error. I have encountered no build errors. Please help check and advise when you have the chance, thank you.
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
typedef struct student
{
string name;
int quiz1, quiz2, quiz3;
struct student *nxt;
} STUDENT;
class studentsStruct
{
private:
STUDENT *S; //Header of the Student List
public:
void init();
void add(string n, int a, int b, int c);
void del(string n);
void update(string n);
void save();
void retrieve();
void display();
};
int menu();
int updatemenu();
float round2(float x); // function to round the average and limit to 2 decimal points
int main()
{
studentsStruct ars;
string nm;
int a, b, c;
ars.init(); // Initialize the S Header of the Student List
ars.retrieve(); // Check if the "studentsdb.txt" is available and load the data as needed
while (1)
{
switch (menu())
{
case 1:
system("cls");
cout << "Insert Mode" << endl;
cout << "Name: ";
cin >> nm;
cout << "Input Quiz 1: ";
cin >> a;
cout << "Input Quiz 2: ";
cin >> b;
cout << "Input Quiz 3: ";
cin >> c;
ars.add(nm, a, b, c);
break;
case 2:
system("cls");
cout << "Update Mode" << endl;
cout << "Input Students Name: ";
cin >> nm;
ars.update(nm);
break;
case 3:
system("cls");
cout << "Delete Mode" << endl;
cout << "Enter Name: ";
cin >> nm;
ars.del(nm);
break;
case 4:
ars.display();
break;
case 5:
ars.save();
exit(0);
default:
cout << "1 to 5 only. ";
system("pause");
}
}
return 0;
}
void studentsStruct::init()
{
S = NULL;
}
void studentsStruct::add(string n, int a, int b, int c)
{
STUDENT *p, *q, *temp;
p = q = S;
temp = new STUDENT;
temp->name = n;
temp->quiz1 = a;
temp->quiz2 = b;
temp->quiz3 = c;
while (p != NULL)
{
q = p;
p = p->nxt;
}
if (p == S)
{
S = temp;
}
else
{
q->nxt = temp;
temp->nxt = p;
}
}
void studentsStruct::del(string n)
{
STUDENT *p, *q;
p = q = S;
while (p != NULL && p->name != n)
{
q = p;
p = p->nxt;
}
if (p == NULL)
{
cout << n << (" is not found.") << endl;
system("pause");
}
else
{
if (p == S)
{
S = S->nxt;
}
else
{
q->nxt = p->nxt;
delete (p);
cout << n << (" is deleted from the student records") << endl;
}
}
}
void studentsStruct::update(string n)
{
STUDENT *p, *q;
p = q = S;
int ua, ub, uc;
while (p != NULL && p->name != n)
{
q = p;
p = p->nxt;
}
if (p == NULL)
{
cout << ("Not Found") << endl;
system("pause");
}
else
{
while (1)
{
cout << "Update Mode" << endl;
cout << "Student : " << p->name << endl;
cout << "Quiz 1 Grade: " << p->quiz1 << endl;
cout << "Quiz 2 Grade: " << p->quiz2 << endl;
cout << "Quiz 3 Grade: " << p->quiz3 << endl;
switch (updatemenu())
{
case 1:
cout << "Quiz 1 Grade: ";
cin >> ua;
p->quiz1 = ua;
save();
break;
case 2:
cout << "Quiz 2 Grade: ";
cin >> ub;
p->quiz2 = ub;
save();
break;
case 3:
cout << "Quiz 3 Grade: ";
cin >> uc;
p->quiz3 = uc;
save();
break;
case 4:
main();
save();
break;
default:
cout << "Select an option between 1 to 3" << endl;
cout << "or select 4 to exit the Update Menu: " << endl;
}
}
}
}
int updatemenu()
{
int um;
cout << "Update Menu" << endl;
cout << "1.) Update Quiz 1 Grade" << endl;
cout << "2.) Update Quiz 2 Grade" << endl;
cout << "3.) Update Quiz 3 Grade" << endl;
cout << "4.) Return to the Main Menu" << endl;
cout << "Select an option between 1 to 3" << endl;
cout << "or select 4 to exit the Update Menu: ";
cin >> um;
return (um);
}
void studentsStruct::display()
{
STUDENT *p;
int i = 1;
p = S;
float ave;
string remarks;
system("cls");
cout << "No.\tName\tQuiz 1\tQuiz 2\tQuiz 3\tAverage\tRemarks\n";
while (p != NULL)
{
ave = (p->quiz1 + p->quiz2 + p->quiz3) / 3.0;
remarks = ave >= 75 ? "Passed" : "Failed";
cout << i++ << ".)\t" << p->name << "\t" << p->quiz1 << "\t" << p->quiz2 << "\t" << p->quiz3 << "\t" << round2(ave) << "\t" << remarks << endl;
p = p->nxt;
}
system("pause");
}
int menu()
{
int op;
cout << "Menu" << endl;
cout << "1.) Insert" << endl;
cout << "2.) Update" << endl;
cout << "3.) Delete" << endl;
cout << "4.) Display" << endl;
cout << "5.) Exit" << endl;
cout << "Select(1-5): ";
cin >> op;
return (op);
}
// Save the student data to "studentdb.txt" if available and create a file if needed
void studentsStruct::save()
{
STUDENT *p;
p = S;
ofstream stuData;
stuData.open("studentdb.txt");
while (p != NULL)
{
stuData << p->name << " " << p->quiz1 << " " << p->quiz2 << " " << p->quiz3 << endl;
p = p->nxt;
}
stuData.close();
}
// Check if the "studentdb.txt" is available and load the data as needed
void studentsStruct::retrieve()
{
ifstream fp;
string n;
int ax, by, cz;
fp.open("studentdb.txt");
if (fp.peek() != std::ifstream::traits_type::eof())
{
while (fp >> n >> ax >> by >> cz)
{
add(n, ax, by, cz);
}
}
else
{
cout << "The file is available but contains no records" << endl;
}
fp.close();
}
// function to round the average and limit to 2 decimal points
float round2(float x)
{
return trunc(x * 100.0) / 100.0;
}
And this is the error I am encountering (see screenshot below):
I created a simple doubly linked list to store data about the plant. I needed to make the data write and read from a file c++. There were no problems with writing to the file. But I have no idea how to properly read data from a file(. Maybe there are some features.
Earlier, when I wrote data from a file to an array, I sorted through the elements using a loop, by index. but now when I need to write the elements in a double linked list - I really do not understand what to do.
Here is my code:
#include <iostream>
#include <cstring>
#include <list>
#include <fstream>
#include <locale>
#include <cstdlib>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <list>
using namespace std;
typedef struct
{
char plant[100];
char family[100];
char species[100];
}BOOK;
typedef struct tag_obj
{
BOOK b;
struct tag_obj* prev, * next;
}OBJ;
OBJ* head = NULL, * tail = NULL;
void add_obj(OBJ* obj, BOOK book, char sim[50]) {
OBJ* c = head;
while (c != NULL) {
if (strcmp(c->b.plant, sim) == 0){
cout<< " element already existst(("<< endl;
return ;
}
c = c->next;
}
OBJ* ptr = new OBJ;
ptr->b = book;
ptr->prev = obj;
ptr->next = (obj == NULL) ? NULL : obj->next;
if (obj != NULL) {
obj->next = ptr;
if (obj->next != NULL) obj->next->prev = ptr;
}
if (ptr->prev == NULL) head = ptr;
if (ptr->next == NULL) tail = ptr;
}
void del_obj(OBJ* obj) {
char x[50];
cout << "enter the name of the plant whose data you want to delete: ";
cin >> x;
OBJ* tmp;
OBJ* h;
if (head == NULL)
{
cout << "List empty,nothing to delete" << endl;
return;
}
if (strcmp(head->b.plant, x) == 0)
{
tmp = head;
head = head->next;
head->prev = NULL;
cout << "Element Deleted" << endl;
free(tmp);
return;
}
h = head;
while (h->next->next != NULL)
{
if (strcmp(h->next->b.plant, x) == 0)
{
tmp = h->next;
h->next = tmp->next;
tmp->next->prev = h;
cout << "Element Deleted" << endl;
free(tmp);
return;
}
h = h->next;
}
if (strcmp(h->next->b.plant, x) == 0)
{
tmp = h->next;
free(tmp);
h->next = NULL;
cout << "Element Deleted" << endl;
return;
}
cout << "Element " << x << " not found" << endl;
}
void show() {
OBJ* c = head;
int d = 1;
while (c != NULL) {
cout << d << ")" << " " << c->b.plant << " " << c->b.family << " " << c->b.species << endl;
c = c->next;
d++;
}
}
int main() {
//setlocale(LC_ALL, "ukr");
ofstream fout;
fout.open("plant account.txt", ios::app);
ifstream fin;
fin.open("plant account.txt");
if (!fout.is_open())
{
cout << "Помилка вiдкриття файлу";
return 1;
}
char sim[50];
BOOK book = { " PLANT "," FAMILY " };
//add_obj(tail, book);
int choice;
cout << "**plant account**" << endl;
cout << "1(add an element)" << endl;
cout << "2(delete)" << endl;
cout << "3(show)" << endl;
cout << "4(exit)" << endl << endl;
start:
cout << " Choose action : ";
cin >> choice;
switch (choice)
{
case 1:
fout << endl;
cout << "Plant name: ";
cin >> book.plant;
strcpy_s(sim, book.plant);
fout << book.plant << " ";
cout << "Plant family: ";
cin >> book.family;
fout << book.family << " ";
cout << "Plant species: ";
cin >> book.species;
fout << book.species << " ";
add_obj(tail, book,sim);
cout << endl;
goto start;
case 2:
del_obj(head);
cout << endl;
goto start;
case 3:
show();
cout << endl;
goto start;
case 4:
cout << " " << endl;
exit(222);
default:
break;
}
fout.close();
fin.close();
return 0;
}
Meet multiple problems while coding, I want to build a room reservation system with linked list,
I want the user can see the room number in the menu and when the room number is taken, the room number will be deleted from the menu.
Is there anyways to simplified the codes, my codes is very messy, please help thanks
1.First I used
struct nodes{
int single_room[5] = {101,102,103,104,105};
int double_room[4] = {201,202,203,204,205};
};
But when I want to compare the Linked List with user input it came out errors
void reservation::UpdateReservation(){
int x;
node *current;
current = head;
bool found;
found = false;
cout << "Please enter your room number to update your reservation:
";
cin >> x;
while ((current != NULL) && (!found))
{
if (current -> single_room == x)
found = true;
else
current = current -> link;
}
while(found)
{
cout <<"The number is exist";
cout << endl;
return found;
cout << value;
}
cout << "The number is not found";
cout << endl;
}
}
It came up an error with ISO C++ forbids comparison between pointer and integer.
After I put a for loop, for the single_room[i], but the current -> single_room[i] is empty..
I've stackoverflowed a lot of questions and found out I can't initialize a linked list, so I used one by one initialize value inside the notes
#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
using namespace std;
class reservation{
private:
struct node
{
int single_room;
int double_room;
int deluxe_suite;
int president_suite;
int room_number;
string name;
int phone_number;
int date;
int number_of_nights;
int number_of_pax;
int time;
node *link;
}*head;
public:
reservation();
void InitializeValue_single_room(int a);
void InitializeValue_double_room(int b);
void InitializeValue_deluxe_suite(int c);
void InitializeValue_president_suite(int d);
void menu();
void Room_size();
void InsertReservation();
void UpdateReservation();
// void DeleteReservation();
void DisplayReservation();
~reservation();
};
reservation::reservation()
{
head = NULL;
}
reservation::~reservation()
{
node *q;
if (head == NULL)
{
return;
}
while (head != NULL)
{
q = head->link;
delete head;
head = q;
}
}
void reservation::InitializeValue_single_room(int a)
{
node *newNode;
newNode = new node;
newNode -> single_room = a;
newNode -> link = head;
head = newNode;
}
void reservation::InitializeValue_double_room(int b)
{
node *newNode;
newNode = new node;
newNode -> double_room = b;
newNode -> link = head;
head = newNode;
}
void reservation::InitializeValue_deluxe_suite(int c)
{
node *newNode;
newNode = new node;
newNode -> deluxe_suite= c;
newNode -> link = head;
head = newNode;
}
void reservation::InitializeValue_president_suite(int d)
{
node *newNode;
newNode = new node;
newNode -> president_suite = d;
newNode -> link = head;
head = newNode;
}
void reservation::menu()
{
cout <<" 1. Book a reservation" << endl;
cout <<" 2. Update a reservation" << endl;
cout <<" 3. Delete a resevation" << endl;
cout <<" 4. Display the reservation" << endl;
cout <<" 5. Help" << endl;
cout <<" 6. Exit" << endl << endl;
cout << "Please enter here: ";
}
But I want to print out the value in the Room_size(), it would print out this
Sorry not enough reputation to upload an image, I just describe here, it would came out|01704272||1704272||1704272||1704272||
1704272||1704272||1704272||1704272||1728736||101||102||103||104||105|
It would print out the numbers which I don't want, I only want 101,102,103,104,105 to view
void reservation::Room_size()
{
node guest;
node *current, *current1;
current = head;
current1 = head;
cout << " Single Room: " << endl;
cout << " ";
while (current != NULL)
{
cout << current -> single_room;
current = current -> link;
if(current != NULL)
cout << "|" << "|";
}
cout << "|" << endl;
cout << " Double Room: " << endl;
cout << " ";
while (current1 != NULL)
{
cout << current1 -> double_room;
current1 = current1 -> link;
if(current1 != NULL)
cout << "|" << "|";
}
cout << "|" << endl;
}
void reservation::InsertReservation()
{
node guest;
node *current;
current = head;
bool found;
found = false;
char b;
int c;
bool d = true;
bool f = false;
do{
ofstream file;
file.open("Guest info.txt", ios::out|ios::app);
if(!file)
{
cout << "ERROR: File can't open";
system("pause");
}
cout<<"Please enter your Name: ";
getline(cin,guest.name);
cout << endl;
while(!f){
cout << "Please enter your phone number: +";
cin >> guest.phone_number;
if(guest.phone_number < 10)//|| (cin >> guest.phone_number) < 11)
{
cout << "Wrong input! ";
f = false;
}
else{
f = true;
cin.ignore();
}
cout << endl;
}
cout << "Please enter the date you want to book: (20/04): ";
cin >> guest.date;
cout << endl;
cout << "Please enter the number of nights you want to stay: ";
cin >> guest.number_of_nights ;
cout << endl;
cout << "Please enter the time you want to check in (24:00 format): ";
cin >> guest.time;
cout << endl;
cout << "Please enter the number of people you have: ";
cin >> guest.number_of_pax;
while(d){
cout << "1.Single Room\n2.Double Room \n3.Luxury Suite \n4.President Suite\n\n";
cout << "Please select the room you want: ";
cin >> c;
if(c==1)
{
cout << " Rooms that are available: " << endl;
cout << " Single rooms: " << endl;
cout << " |" << guest.single_room << "|";
cout << endl << endl;
cout << "Please enter the room number you want to book: ";
cin >> guest.room_number;
d = false;
}else if(c==2)
{
cout << " Rooms that are available: " << endl;
cout << " Double rooms: " << endl;
cout << " |" << guest.double_room << "|";
cout << endl << endl;
cout << "Please enter the room number you want to book: ";
cin >> guest.room_number;
d = false;
}else if(c==3)
{
cout << " Rooms that are available: " << endl;
cout << " Luxury Suite: " << endl;
cout << " |" << guest.deluxe_suite << "|";
cout << endl << endl;
cout << "Please enter the room number you want to book: ";
cin >> guest.room_number;
d = false;
}else if (c==4)
{
cout << " Rooms that are available: " << endl;
cout << " President Suite" << endl;
cout << " |" << guest.president_suite << "|";
cout << endl << endl;
cout << "Please enter the room number you want to book: ";
cin >> guest.room_number;
d = false;
}else
{
cout << "Wrong input. Please try again";
d = true;
}
}
int e;
cout << "Press 1 to Save or 2 to cancel:";
cout << endl;
cin >> e;
if(e==1)
{
cout << endl;
file << "Guests info" << endl;
cout << endl;
file << "=================================================="<< endl;
file << endl;
file << "Room Number: " << guest.room_number;
file << endl;
file << "Name: " << guest.name << endl;
file << endl;
file << "Phone Number: " << guest.phone_number << endl;
file << endl;
file << "Date: " << guest.date << endl;
file << endl;
file << "Number of nights: " << guest.number_of_nights << endl;
file << endl;
file << "Time: " << guest.time << endl;
file << endl;
file << "Number of pax: " << guest.number_of_pax << endl;
file << endl;
file << endl;
file << "====================================================" << endl;
file.close();
cout << "Record Saved " << endl;
cout << "======================================================" << endl;
}else
{
cout << "Record was not saved " << endl;
cout << "====================================================" << endl;
cout << endl;
}
/* while ((current != NULL) && (!found))
{
if (current -> single_room == (guest.room_number))
found = true;
else
current = current -> link;
while(found)
{
cout << "ROOM NUMBER FOUND";
cout << endl;
}
cout << "NO";
cout << endl;
}*/
cout << "Enter (Y/y) to input another data or enter (N/n) to Exit";
cin >> b;
cout << "======================================================" <<
endl;
cout << endl;
}while(b == 'y' || b == 'Y');
if(b =='y'|| b=='Y')
{
cin.ignore();
}
}
void reservation::DisplayReservation()
{
node *current;
current = head;
cout << " |";
while (current != NULL)//) && current-> deluxe_suite <400))
{
cout << current -> deluxe_suite;
current = current -> link;
if(current != NULL)
cout << "| "<< "|";
}
cout << "|" << endl;
}
int main()
{
reservation r;
r.InitializeValue_single_room(105);
r.InitializeValue_single_room(104);
r.InitializeValue_single_room(103);
r.InitializeValue_single_room(102);
r.InitializeValue_single_room(101);
r.InitializeValue_double_room(204);
r.InitializeValue_double_room(203);
r.InitializeValue_double_room(202);
r.InitializeValue_double_room(201);
r.InitializeValue_deluxe_suite(303);
r.InitializeValue_deluxe_suite(302);
r.InitializeValue_deluxe_suite(301);
r.InitializeValue_president_suite(888);
r.InitializeValue_president_suite(666);
cout <<"================================================" << endl << endl;
cout <<" Welcome to the Hotel Reservation Application" << endl << endl;
cout <<"================================================" << endl;
int a;
cout << "Please wait while the system is analyzing hte data\n";
cout << endl;
cout<<"===================================" << endl;
cout <<" Main Menu " << endl << endl;
cout << " Rooms that are available: " << endl;
r.Room_size();
cout << endl << endl;
cout << "===================================" << endl;
r.menu();
cin >> a;
if(a == 1)
{
system("CLS");
cout << "===================================" << endl;
cout << " BOOK A RESERVATION" << endl;
cout << "===================================" << endl;
cin.ignore();
r.InsertReservation();
}else if(a == 2)
{
system("CLS");
cout << "===================================" << endl;
cout << " UPDATE YOUR RESERVATION" << endl;
cout << "===================================" << endl;
cin.ignore();
// r.UpdateReservation();
}else if(a == 4)
{
system("CLS");
cout <<"===================================" << endl;
cout << " VIEW ALL RESERVATION" << endl;
cout << "===================================" << endl;
cin.ignore();
r.DisplayReservation();
}
return 0;
}
I just ran your code.
What is happening is that you have single rooms, double, delux and president suite rooms in the same class, with the same list. It's not the best way to go, but it is a way to go.
This is the result that I got
Rooms that are available:
Single Room:
0||0||0||0||0||0||0||0||0||101||102||103||104||105|
Double Room:
0||0||0||0||0||201||202||203||204||0||0||-805306368||-805306368||-805306368|
You initialised the list as
r.InitializeValue_single_room(105);
r.InitializeValue_single_room(104);
r.InitializeValue_single_room(103);
r.InitializeValue_single_room(102);
r.InitializeValue_single_room(101);
r.InitializeValue_double_room(204);
r.InitializeValue_double_room(203);
r.InitializeValue_double_room(202);
r.InitializeValue_double_room(201);
r.InitializeValue_deluxe_suite(303);
r.InitializeValue_deluxe_suite(302);
r.InitializeValue_deluxe_suite(301);
r.InitializeValue_president_suite(888);
r.InitializeValue_president_suite(666);
Since the list is last in first out type, when you iterate through the list in the Room_size() function your function sees the following in the list
The first 2 rooms are president suites, where only president_suite attribute is set
The next 3 rooms are delux, where only deluxe_suite attribute is set
the next 4 rooms are double, where only double_room attribute is set
and the last 5 rooms are, where only single room attribute is set
So when it is printing single rooms, the first 9 nodes do not have the single room attribute set, as such it prints some garbage value, 5 times and then prints the correct single room number, and
Similarly for double room, it prints 5 garbage values and then prints the right numbers, and then 5 more garbage values.
to correct this problem you need to make the following changes.
1) In the class definition, use a single variable for room number, and another variable for room type.
2) Set room type constants using enum
enum room_types={single,double,delux,president_suite}
3) When a room is initialised via the InitializeValue_**, the function should set the room number from the arguments to the room number in the node, but should set room type attribute as per the enum. for example in the InitializeValue_single_room function
void reservation::InitializeValue_single_room(int a)
{
node *newNode;
newNode = new node;
newNode -> room_number = a;
newNode -> room_type = single;
newNode -> link = head;
head = newNode;
}
4) When you call the room_size() function, while printing the room types check for the room type. Example :
cout << " Single Room: " << endl;
cout << " ";
while (current != NULL)
{
if(current -> room_type !=single){
current = current -> link;
continue;
}
cout << current -> room_number;
current = current -> link;
if(current != NULL)
cout << "|" << "|";
}
I hope this helps.
There are much better ways to implement this, but I believe this is the best way for you for now.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
)
I'm working on a code... almost finished but I'm stuck with one last thing,
I need to find a way to edit a client's info when the user wishes to.
this is my code... any one can tell me what's wrong please? :
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
ifstream infile;
ofstream outfile;
struct INFO {
int id;
string name;
unsigned balance;
long phone;
};
class Node
{
public:
INFO data;
Node *left;
Node *right;
Node() {
data.id = 0;
data.name = "NULL";
data.phone = 0;
data.balance = 0;
}
Node(INFO a)
{
data = a;
left = 0;
right = 0;
}
};
class Tree
{
public:
Node *root;
INFO inf;
Node *zero;
Tree()
{
root = 0;
}
bool insert(INFO inf)
{
if (root == 0)
{
root = new Node(inf);
return true;
}
Node *p = root;
Node *q = root;
while (p != 0)
{
q = p;
if (p->data.id == inf.id)
return false;
if (p->data.id > inf.id)
p = p->left;
else
p = p->right;
}
if (inf.id < q->data.id)
q->left = new Node(inf);
else
q->right = new Node(inf);
return true;
}
bool searchid(Node *p, int y)
{
if (p != 0) {
if (p->data.id == y) {
cout << "ID: ";
cout << p->data.id << "\t";
cout << "Name: ";
cout << p->data.name << "\t";
cout << "Balance: ";
cout << p->data.balance << "\t";
cout << "Phone number: ";
cout << p->data.phone << endl;
cout << "_________________" << endl;
return true;
}
}
if (p->left != 0) {
if (searchid(p->left, y)) {
return true;
}
}
if (p->right != 0) {
if (searchid(p->right, y)) {
return true;
}
}
return false;
}
Node SAD(int id) {
Node *p = root;
if (p->data.id == id) {
Node *q = p;
return *p;
}
if (p->left != 0)
SAD(p->left->data.id);
if (p->right != 0)
SAD(p->right->data.id);
return *zero;
}
void edit(int q) {
Node p = SAD(q);
cout << "The ID is: " << p.data.id << endl;
cout << "The account owner: ";
cout << p.data.name << endl;
cout << "Do you want to edit the owner?(Y/N) ";
char x;
cin >> x;
if (x == 'Y' || x == 'y') {
string New;
cout << "Enter the new owner name: ";
cin >> New;
p.data.name = New;
}
cout << "The Balance in the account is: ";
cout << p.data.balance << endl;
cout << "Do you want to edit the balance?(Y/N) ";
cin >> x;
if (x == 'Y' || x == 'y') {
int New;
cout << "Enter the new Balance: ";
cin >> New;
p.data.balance = New;
}
cout << "The phone number is: ";
cout << p.data.phone << endl;
cout << "Do you want to edit the phone number?(Y/N) ";
cin >> x;
if (x == 'Y' || x == 'y') {
long New;
cout << "Enter the new phone number";
cin >> New;
p.data.phone = New;
}
cout << p.data.id << " " << p.data.name << " " << p.data.balance << " " << p.data.phone << endl;
insert(p.data);
}
void print(Node *p)
{
if (p != 0) {
cout << "ID: ";
cout << p->data.id << "\t";
cout << "Name: ";
cout << p->data.name << "\t";
cout << "Balance: ";
cout << p->data.balance << "\t";
cout << "Phone number: ";
cout << p->data.phone << endl;
cout << "_______________________________________________________________" << endl<<endl;
}
if (p->left != 0)
print(p->left);
if (p->right != 0)
print(p->right);
}
void store(Node *p)
{
if (p != 0) {
outfile << "ID: ";
outfile << p->data.id << " ";
outfile << "Name: ";
outfile << p->data.name << " ";
outfile << "Balance: ";
outfile << p->data.balance << " ";
outfile << "Phone number: ";
outfile << p->data.phone << endl;
outfile << "_______________________________________________________________" << endl;
}
if (p->left != 0)
store(p->left);
if (p->right != 0)
store(p->right);
}
bool searchname(Node *p, string x)
{
Node *q = root;
q = p;
while (p != 0) {
if (p->data.name == x) {
cout << "ID: " << p->data.id << "\t";
cout << "Name: " << p->data.name << "\t";
cout << "Balance: " << p->data.balance << "\t";
cout << "Phone number: " << p->data.phone << endl;
}
else {
}
}
}
};
void main()
{
outfile.open("clients.txt");
int opt;
Tree t;
int m = 1;
while (m != 0) {
cout << "Choose an option:" << endl << "1- To Add new clients." << endl << "2- To Display the clients." << endl << "3- To Store the clients in a Text Document." << endl << "4- To Search for a specific client through it's ID." << endl << "5- To Edit a specific client's information" << endl << "6- To Delete a specific client." <<endl<<"7- Exit."<< endl;
cin >> opt;
switch (opt) {
case 1:
int n;
cout << "Enter the amount of clients: ";
cin >> n;
INFO *arr;
arr = new INFO[n];
cout << "Enter the elements of the array: " << endl;
for (int i = 0; i < n; i++)
{
cout << "Client #" << i + 1 << endl << "-----------" << endl;
cout << "Enter the ID: ";
cin >> arr[i].id;
cout << "Enter the name of the client: ";
cin >> arr[i].name;
cout << "Enter the balance: ";
cin >> arr[i].balance;
cout << "Enter the phone number: ";
cin >> arr[i].phone;
t.insert(arr[i]);
}
break;
case 2:
t.print(t.root);
break;
case 3:
t.store(t.root);
cout << "Saved!" << endl << "in directory: C:/Users/Taiseer/Documents/Visual Studio 2015/Projects/ADS Project/ADS Project" << endl;
break;
case 4:
cout << endl;
int s;
cout << "What element do you want to search for? ";
cin >> s;
if (t.searchid(t.root, s) == false) {
cout << " Not here.... :( \n";
}
cout << endl;
break;
case 5:
char x;
cin >> x;
if (x == 'y' || x == 'Y') {
int id;
cout << "Enter the id you want to edit: ";
cin >> id;
t.edit(id);
}
else
return;
break;
case 6:
break;
case 7:
m = 0;
break;
default:
cout << "lol" << endl;
}
}
}
The problem is that Tree::SAD() returns the node that is being searched for by value. This means that in Tree::edit(), the following line:
Node p = SAD(q);
Gets a copy of the actual node. Anything changed in p is not changed in the actual Tree. At the end of edit(), you try to insert(p.data), but this does not do anything, because your implementation of insert() never overwrites already existing nodes.
One solution is to make SAD() return a pointer to the found node. This has the added benefit that you can return nullptr to signal the case where the searched for id does not exist. This can then be used in edit() to change the fields of the Node structure directly.
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 !!!