read data from a file in a double linked list - c++

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

Related

Deletion in Binary Search Tree for strings

This program is a binary search tree of string to store information of students with the following details such as id, name and CGPA. And using unique id of a student to search, delete and insert different data. But in deletion when a subtree is involved the tree gets separated, I don't know what I'm doing wrong.
#include <iostream>
using namespace std;
struct BstNode
{
string iD;
string name;
float cgpa;
BstNode *left;
BstNode *right;
};
BstNode *root;
BstNode *GetNewNode(string iD0, string n0, float cg0)
{
BstNode *NewNode = new BstNode();
NewNode->iD = iD0;
NewNode->name = n0;
NewNode->cgpa = cg0;
NewNode->left = NULL;
NewNode->right = NULL;
return NewNode;
}
void PreOrder(BstNode *root)
{
if (root == NULL)
{
return;
}
cout << "ID: " << root->iD << "\nNAME: " << root->name << "\nCGPA: " << root->cgpa << endl;
PreOrder(root->left);
PreOrder(root->right);
}
void InOrder(BstNode *root)
{
if (root == NULL)
{
return;
}
InOrder(root->left);
cout << "ID: " << root->iD << "\nNAME: " << root->name << "\nCGPA: " << root->cgpa << endl;
InOrder(root->right);
}
void PostOrder(BstNode *root)
{
if (root == NULL)
{
return;
}
PostOrder(root->left);
PostOrder(root->right);
cout << "ID: " << root->iD << "\nNAME: " << root->name << "\nCGPA: " << root->cgpa << endl;
cout << endl;
}
BstNode *Insert(BstNode *root, string iD2, string n2, float cg2)
{
if (root == NULL)
{
root = GetNewNode(iD2, n2, cg2);
}
else if (iD2 <= root->iD)
{
root->left = Insert(root->left, iD2, n2, cg2);
}
else
{
root->right = Insert(root->right, iD2, n2, cg2);
}
return root;
}
BstNode *Rectify(BstNode *root, string id1, string n, float cg)
{
root->iD = id1;
root->name = n;
root->cgpa = cg;
return root;
}
struct BstNode *FindMin(BstNode *root)
{
struct BstNode* current = root;
/* loop down to find the leftmost leaf */
while (current && current->left != NULL)
current = current->left;
return current;
}
BstNode *Delete(BstNode *root, string data)
{
if (root == NULL)
return root;
else
{
if (data < root->iD)
root->left = Delete(root->left, data);
else if (data > root->iD)
root->right = Delete(root->right, data);
else
{
if (root->left == NULL and root->right == NULL)
return NULL;
else if (root->left == NULL)
{
struct BstNode *temp = root->right;
delete(root);
return temp;
}
else if (root->right == NULL)
{
struct BstNode *temp = root->left;
delete(root);
return temp;
}
else
{
struct BstNode *temp = FindMin(root->right);
root->iD = temp->iD;
root->name = temp->name;
root->cgpa = temp->cgpa;
root->right = Delete(root->right, temp->iD);
}
}
return root;
}
}
BstNode *Search(BstNode * root, string iDs)
{
cout << "Finding " << endl;
if (root == NULL)
{
cout << "No such info!" << endl;
return root;
}
else if (root->iD == iDs)
{
cout << "Found 0 " << endl;
cout << "ID: " << root->iD << endl;
cout << "NAME: " << root->name << endl;
cout << "CGPA: " << root->cgpa << endl;
bool done = false;
while (!done)
{
cout << "Would you like to update this student's information? [y/n]\n";
string x;
cin >> x;
if (x == "y")
{
cout << "The following fields are updatable:\n";
cout << "1. Student ID\n";
cout << "2. Student Name\n";
cout << "3. Student CGPA\n";
cout << "4. Remove Student\n";
cout << "Enter your choice:\n";
bool done1 = false;
while (!done1)
{
int ch;
cin >> ch;
if (ch == 1)
{
cout << "Please enter new ID: \n";
string nwid;
cin >> nwid;
cout << "============================" << endl;
cout << "Updating \n";
cout << "============================" << endl;
root = Rectify(root, nwid, root->name, root->cgpa);
cout << "============================" << endl;
cout << "Updated Successfully! \n";
cout << "============================" << endl;
cout << "============================" << endl;
cout << root->iD << endl;
cout << root->name << endl;
cout << root->cgpa << endl;
cout << "============================" << endl;
done1 = true;
}
else if (ch == 2)
{
cout << "Please enter new name: \n";
string nwname;
cin >> nwname;
cout << "============================" << endl;
cout << "Updating \n";
cout << "============================" << endl;
root = Rectify(root, root->iD, nwname, root->cgpa);
cout << "============================" << endl;
cout << "Updated Successfully! \n";
cout << "============================" << endl;
cout << "============================" << endl;
cout << root->iD << endl;
cout << root->name << endl;
cout << root->cgpa << endl;
cout << "============================" << endl;
done1 = true;
}
else if (ch == 3)
{
cout << "Please enter new CGPA: \n";
float nwcg;
cin >> nwcg;
cout << "============================" << endl;
cout << "Updating \n";
cout << "============================" << endl;
root = Rectify(root, root->iD, root->name, nwcg);
cout << "============================" << endl;
cout << "Updated Successfully! \n";
cout << "============================" << endl;
cout << "============================" << endl;
cout << root->iD << endl;
cout << root->name << endl;
cout << root->cgpa << endl;
cout << "============================" << endl;
done1 = true;
}
else if (ch == 4)
{
cout << "Removing\n";
root = Delete(root, root->iD);
cout << "Removed!\n";
return root;
done1 = true;
}
else
{
cout << "Wrong input try again! \n";
}
}
done = true;
}
else if (x == "n")
{
done = true;
}
else
{
cout << "Wrong input try again! \n";
}
}
return root;
}
else if (iDs <= root->iD)
{
return Search(root->left, iDs);
}
else
{
return Search(root->right, iDs);
}
}
int main()
{
root = NULL;
root = Insert(root, "21-44631-1", "Rafiul", 3.75);
root = Insert(root, "21-44531-1", "Haque", 4.0);
root = Insert(root, "21-44431-1", "Rafsun", 3.78);
root = Insert(root, "21-44331-1", "Rafi", 3.5);
root = Insert(root, "21-44231-1", "ABC", 4.0);
root = Insert(root, "21-44611-1", "AC", 4.0);
cout << "Please enter the ID you want to search: ";
string s;
cin >> s;
cout << endl;
Search(root, s);
cout << "Reading tree in preorder : \n";
PreOrder(root);
cout<<"============================"<< endl;
cout << "\nReading tree in inorder : \n";
InOrder(root);
cout<<"============================"<< endl;
cout << "\nReading tree in postorder : \n";
PostOrder(root);
cout << "============================" << endl;
}
Deleting a BST node from a simple (e.g. non-self-balancing) implementation involves three things:
Find the node you're deleting. More specifically, find the pointer in the tree (which may be the root pointer) that points to the node you want to delete.
Once found, promote one of the children to occupy the vacancy about to be left by the node being deleted.
Hang the opposite child (if there even is one) in the left (or right, depending on which child you promoted in (2), position possible of the promoted child.
Note that it is possible to cover all four node+children cases (no children, only a left child, only a right child, or both), using a single algorithm, especially when using a pointer-to-pointer to iterate the tree. It is done like this (liberally commented to try and explain what is going on):
BstNode *Delete(BstNode *root, string data)
{
BstNode **pp = &root;
// find the node we want to delete by id
while (*pp)
{
if (data < (*pp)->iD)
pp = &(*pp)->left;
else if ((*pp)->iD < data)
pp = &(*pp)->right;
else // equivalent. fount it
break;
}
// if this is non-null, we found the pointer in the
// tree that points to the node we want to delete.
// note that this could even be the root pointer
// where we started.
if (*pp)
{
// remember the node. we're about to overwrite
// the tree pointer that is referring to it.
BstNode *victim = *pp;
// always promote the right node.
*pp = victim->right;
// now iterate down the opposite side of the
// note we just promoted, looking for the first
// null slot on which we can hang our sibling
// (if there even is one; it's ok if there isn't)
while (*pp)
pp = &(*pp)->left;
// this is where we hang the sibling node
*pp = victim->left;
// the tree is fixed up and the node excised. we
// can delete it now.
delete victim;
}
// return this. remember, root may have been pointing
// to the node we deleted, and if so, it has changed
// so we need to inform the caller by return result.
return root;
}
Sans the overt comments explaining what is happening, it is a surprisingly small amount of code, especially when you consider what it is accomplishing.

Storing data in a doubly linked list

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

Error after execution of c++ code

After execution, I am getting following errors in Visual C++ 2015:
while (c< pos - 1)
error: identifier c undefined
clrscr();
error: identifier clrscr(); is undefined
case 6: display(head);
error: identifier display is undefined
Here is my code:
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
struct library
{
char author[20], title[20], pub[20];
int price;
library *next;
};
int sum = 0;
void main()
{
clrscr();
library *head = NULL;
library *initial(void);
library *purchase(library *);
void stock(library *);
void search(library *);
int choice;
while (1)
{
cout << "Mtavari\n";
cout << "1) Sawyisi monacemebi\n";
cout << "2) Yidvebi\n";
cout << "3) Gayidvebi\n";
cout << "4) Wignebi\n";
cout << "5) Dzieba\n";
cout << "6) Wignebis nuskha\n";
cout << "7) Gamosvla\n";
cout << "Airchiet:-";
cin >> choice;
switch (choice)
{
case 1: head = initial();
getch();
break;
case 2: head = purchase(head);
getch();
break;
getch();
break;
case 5: search(head);
getch();
break;
case 6: display(head);
getch();
break;
case 7: goto out;
default: cout << "\nShecdomiti archevani\n";
}
clrscr();
}
out:
}
library *initial(void)
{
clrscr();
library *newl = NULL, *start = NULL, *end = newl;
char ch;
while (1)
{
cout << "\n\nSheiyvanet y an Y\n";
cout << "Gsurt archeva:-";
cin >> ch;
if (ch == 'y' || ch == 'Y')
{
newl = new library;
cout << "\n\nSheiyvanet wignis avtori:-";
cin >> newl->author;
cout << "Sheiyvanet satauri:-";
cin >> newl->title;
cout << "Sheiyvanet gamomcemloba:-";
cin >> newl->pub;
cout << "Sheiyvanet fasi:-";
cin >> newl->price;
sum = sum + newl->price;
if (start == NULL)
start = newl;
else
end->next = newl;
end = newl;
end->next = NULL;
}
else break;
}
return(start);
}
library *purchase(library *start)
{
clrscr();
int pos, count = 1, choice;
library *newl, *cnt = start, *head = start;
if (start == NULL)
cout << "\n\nMonacemebi ar aris\n";
cout << "\n\nMtavari\n";
cout << "1) Pirvel adgilze sheyvana\n";
cout << "2) Shuashi chamateba\n";
cout << "3) Bolo poziciaze sheyvana \n";
cout << "4) Gamosvla\n";
cout << "Airchiet:-";
cin >> choice;
if (choice >= 1 && choice <= 3)
{
newl = new library;
cout << "Avtoris saxeli :-";
cin >> newl->author;
cout << "Wignis satauri :-";
cin >> newl->title;
cout << "Gamomcemloba :-";
cin >> newl->pub;
cout << "Fasi:-";
cin >> newl->price;
sum = sum + newl->price;
}
switch (choice)
{
case 1:
newl->next = head;
head = newl;
break;
case 2:
read:
cout << "\n\nAirchiet pozicia:-";
cin >> pos;
while (cnt != NULL)
{
count++;
cnt = cnt->next;
}
if (pos<1 || pos>count + 1)
{
cout << "\n\nPozicia arasworia\n";
goto read;
}
{
while (c<pos - 1)
{
c++;
start = start->next;
}
}
newl->next = start->next;
start->next = newl;
break;
case 3:
start = start->next;
start->next = newl;
newl->next = NULL;
break;
case 4: goto out;
default: cout << "\nArchevani arasworia\n";
break;
}
out:
return(head);
}
void stock(library *start)
{
clrscr();
int count = 0;
while (start != NULL)
{
count++;
start = start->next;
}
cout << "\n\n\n\tWignebis raodenoba " << count << endl;
cout << "\tMtliani fasi " << sum;
}
void search(library *start)
{
clrscr();
char author[20], title[20];
cout << "Sheiyvanet sadziebo fraza(avtori an wigni...)\n";
cin >> title >> author;
while (start != NULL)
{
if (title == start->title)
{
if (author == start->author)
{
cout << "\n\nArsebuli wignebi\n";
cout << "Girebuleba" << start->price;
return;
}
}
}
cout << "\n\nVer moidzebna\n";
}
void display(library *start)
{
clrscr();
cout << setw(10) << "Satauri" << setw(25) << "Avtori" << setw(25) << "Publikacia" << setw(20) << "Fasi" << endl << endl;
for (int i = 0;i<40;i++)
cout << "=*";
cout << endl;
while (start != NULL)
{
cout << setw(10) << start->title << setw(25) << start->author << setw(25) << start->pub << setw(20) << start->price << endl;
start = start->next;
}
}
At first, clean-up your code (I see, you posted HTML-formated code. So, "thanks" for a challenge to save as HTML-file, open in a browser, then copy-paste away as plain text).
For now, I'm able to tell you what's wrong:
replace void main() with int main(), void main() is legacy and no more correct. Also, you must return 0; at end or return any other number if you wish to tell that your program finished with errors (for example, missing argument or not existing file).
Don't put function prototypes inside main(), put them over main!
I mean:
library *initial(void);
library *purchase(library *);
void stock(library *);
void search(library *);
int main()
{
//...
clrsrc() function is no more exist. Instead, you have to use this function: How do we clear the console in assembly?
missing display() function is caused you forgot to put prototype to it over main() function: void display(library *start);
missing c in while(c < pos - 1): just put int c = 0; over that while loop.
I have been removed using namespace std; and added the std:: to every function requires it.
Tip: Instead of having << std::endl << std::endl you can just do << "\n\n"
So, the full and fixed code will be:
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#ifdef _WIN32
// for Windows
#include <conio.h>
#include <windows.h>
#else
// for Linux (required to install the ncurses-dev and link with -lncurses!)
#include <ncurses.h>
#endif
void clrscr()
{
#ifdef _WIN32
// for Windows
char fill = ' ';
COORD tl = {0,0};
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &s);
DWORD written, cells = s.dwSize.X * s.dwSize.Y;
FillConsoleOutputCharacter(console, fill, cells, tl, &written);
FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);
SetConsoleCursorPosition(console, tl);
#else
// for Linux
system("clear");
#endif
}
struct library
{
char author[20], title[20], pub[20];
int price;
library *next;
};
library *initial(void);
library *purchase(library *);
void stock(library *);
void search(library *);
void display(library *start);
int sum = 0;
int main()
{
clrscr();
library *head = NULL;
int choice;
while (1)
{
std::cout << "Mtavari\n";
std::cout << "1) Sawyisi monacemebi\n";
std::cout << "2) Yidvebi\n";
std::cout << "3) Gayidvebi\n";
std::cout << "4) Wignebi\n";
std::cout << "5) Dzieba\n";
std::cout << "6) Wignebis nuskha\n";
std::cout << "7) Gamosvla\n";
std::cout << "Airchiet:-";
std::cin >> choice;
switch (choice)
{
case 1: head = initial();
getch();
break;
case 2: head = purchase(head);
getch();
break;
getch();
break;
case 5: search(head);
getch();
break;
case 6: display(head);
getch();
break;
case 7:
goto out;
default: std::cout << "\nShecdomiti archevani\n";
}
clrscr();
}
out:
return 0;
}
library *initial(void)
{
clrscr();
library *newl = NULL, *start = NULL, *end = newl;
char ch;
while (1)
{
std::cout << "\n\nSheiyvanet y an Y\n";
std::cout << "Gsurt archeva:-";
std::cin >> ch;
if (ch == 'y' || ch == 'Y')
{
newl = new library;
std::cout << "\n\nSheiyvanet wignis avtori:-";
std::cin >> newl->author;
std::cout << "Sheiyvanet satauri:-";
std::cin >> newl->title;
std::cout << "Sheiyvanet gamomcemloba:-";
std::cin >> newl->pub;
std::cout << "Sheiyvanet fasi:-";
std::cin >> newl->price;
sum = sum + newl->price;
if (start == NULL)
start = newl;
else
end->next = newl;
end = newl;
end->next = NULL;
}
else break;
}
return(start);
}
library *purchase(library *start)
{
clrscr();
int pos, count = 1, choice;
library *newl, *cnt = start, *head = start;
if (start == NULL)
std::cout << "\n\nMonacemebi ar aris\n";
std::cout << "\n\nMtavari\n";
std::cout << "1) Pirvel adgilze sheyvana\n";
std::cout << "2) Shuashi chamateba\n";
std::cout << "3) Bolo poziciaze sheyvana \n";
std::cout << "4) Gamosvla\n";
std::cout << "Airchiet:-";
std::cin >> choice;
if (choice >= 1 && choice <= 3)
{
newl = new library;
std::cout << "Avtoris saxeli :-";
std::cin >> newl->author;
std::cout << "Wignis satauri :-";
std::cin >> newl->title;
std::cout << "Gamomcemloba :-";
std::cin >> newl->pub;
std::cout << "Fasi:-";
std::cin >> newl->price;
sum = sum + newl->price;
}
switch (choice)
{
case 1:
newl->next = head;
head = newl;
break;
case 2:
read:
std::cout << "\n\nAirchiet pozicia:-";
std::cin >> pos;
while (cnt != NULL)
{
count++;
cnt = cnt->next;
}
if (pos<1 || pos>count + 1)
{
std::cout << "\n\nPozicia arasworia\n";
goto read;
}
{
int c = 0;
while(c < pos - 1)
{
c++;
start = start->next;
}
}
newl->next = start->next;
start->next = newl;
break;
case 3:
start = start->next;
start->next = newl;
newl->next = NULL;
break;
case 4:
goto out;
default:
std::cout << "\nArchevani arasworia\n";
break;
}
out:
return(head);
}
void stock(library *start)
{
clrscr();
int count = 0;
while (start != NULL)
{
count++;
start = start->next;
}
std::cout << "\n\n\n\tWignebis raodenoba " << count << std::endl;
std::cout << "\tMtliani fasi " << sum;
}
void search(library *start)
{
clrscr();
char author[20], title[20];
std::cout << "Sheiyvanet sadziebo fraza(avtori an wigni...)\n";
std::cin >> title >> author;
while (start != NULL)
{
if (title == start->title)
{
if (author == start->author)
{
std::cout << "\n\nArsebuli wignebi\n";
std::cout << "Girebuleba" << start->price;
return;
}
}
}
std::cout << "\n\nVer moidzebna\n";
}
void display(library *start)
{
clrscr();
std::cout << std::setw(10) << "Satauri" << std::setw(25) << "Avtori" << std::setw(25) << "Publikacia" << std::setw(20) << "Fasi" << "\n\n";
for (int i = 0;i<40;i++)
std::cout << "=*";
std::cout << std::endl;
while (start != NULL)
{
std::cout << std::setw(10) << start->title << std::setw(25) << start->author << std::setw(25) << start->pub << std::setw(20) << start->price << std::endl;
start = start->next;
}
}
I hope this will help you.
c/c++ is a single-pass language. you have to define functions before they're used. i.e. higher up. The explains why display isn't recognized: you need to either have the function body above where it's used or put an empty declaration in:
void display(library *start);
before it's first used. this tells the compiler what sort of object "display" is. As for clrscr, that depends on the library you're using. check the references for your library.
As for c, you never made a variable called "c", so the compiler doesn't know what that's supposed to be. Neither do we.

Editing a Node in a binary tree structure [closed]

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.

Basic C++ Linked list nodes & Pointer Probs

I've been having trouble trying to retrieve data from the first node in my linked list for quite some time now. Forgive me, but I am still new to C++ and especially pointers and linked lists.
Here is how I am reading the data from my text file (working fine so far)
void readFile(ifstream& budgetFile, budgetItem *newNode, int& counter, budgetItem *temp, budgetItem *header)
{
char pauseChar;
int ctype;
string cname;
double camount;
char cleared;
itemPtr listTop = NULL;
while (!budgetFile.eof())
{
//newNode = new budgetItem;
budgetFile >> ctype >> cname >> camount >> cleared;
newNode->theType = ctype;
cout << newNode->theType << endl;
//cout << ctype << endl;
newNode->name = cname;
cout << newNode->name << endl;
newNode->amount = camount;
cout << newNode->amount << endl;
if (cleared == 'Y') {
newNode->cleared = true;
}
else{
newNode->cleared = false;
}
newNode->next = listTop;
listTop = newNode;
if (counter == 0)
{
header = newNode;
}
counter++;
}
return;
}
And here is how I am trying to retrieve the data starting from the first node. It doesn't work at all. Any help on this would be appreciated.
void showBudget (budgetItem *newNode, budgetItem *temp, budgetItem *header)
{
double incomeTotal;
double expenseTotal;
double differenceTotal;
//itemPtr *newlist;
//newNode = header;
itemPtr listTop;
budgetItem *here = listTop;
do {
cout << "INCOME:" << endl;
cout << " Item Amount Cleared" << endl;
cout << " ---------------- ------- -------" << endl;
if (newNode == NULL)
{
cout << "List is empty." << endl;
}
else
{
if (newNode->theType != 0)
{
cout << " " << newNode->name << setw(23) << fixed << setprecision(2) << newNode->amount << " ";
if (newNode->cleared == true) {
cout << "no" << endl;
}
else{
cout << "yes" << endl;
}
}
else{
cout << endl;
}
}
newNode = newNode->next;
} while (newNode != NULL);
cout << "End of List." << endl;
return;
}
// ...
counter++;
// create next node here:
newNode = new budgetItem;
}
For each new element in the list we need to allocate new object in memory. You were using the same object again and again.