user defined variables on the heap getting destroyed in while loop - c++

I an odd problem that i cant understand if someone could point me in the right direction it would be greatly appreciated.I create my own linked list variables on the heap but when i go to add another variable to it they all get destroyed and i dont know why.
in my main i set up my variables like this
main.cpp
Book* temp;
temp = bookSetUp();
this goes to a different cpp called functions which sets up the objects like this:
functions.cpp
Book* bookSetUp()
{
//The items that populate the list
Book* a= new Book("A Tale of Two Cities", "Charles Dickens", "1", true);
Book* b= new Book("Lord of the rings", "J.R.R Tolkein", "2", true);
Book* c= new Book("Le Petit Prince", "Antoine de Saint-Exupéry", "3", true);
Book* d= new Book("And Then There Were None", "Agatha Christie", "4", true);
Book* e= new Book("Dream of the Red Chamber","Cao Xueqin","5", true);
Book* f= new Book("The Hobbit","J.R.R Tolkein","6", true);
//sets up the pointers between books
a->setPrev(NULL);
a->setNext(b);
b->setPrev(a);
b->setNext(c);
c->setPrev(b);
c->setNext(d);
d->setPrev(c);
d->setNext(e);
e->setPrev(d);
e->setNext(f);
f->setPrev(e);
f->setNext(NULL);
//sets up a temp pointer to a
Book* temp = a;
//returns the temp pointer to a
return temp;
}
this works perfectly but later on when i go to add to the list again in the main using:
main.cpp
else if(checkRegUser(username, password, regUserList) == true)
{
int choice = 99;
cout << "Welcome Registered user: "<< username << endl;
while(choice != 0)
{
//this is so the print will start everytime as if you run it once print will be at NULL thereafter
Book* print = temp;
choice = options();
if(choice == 1)
{
while(print!=NULL)
{
cout<<"Name: "<<print->getName()<<endl<<"Author: "<<print->getAuthor()<<endl<<"ISBN: "<<print->getISBN()<<endl<<"Availability: "<<print->getAvail()<<endl;
cout<<endl;
print = print->getNext();
}
print = temp;
}
if(choice == 2)
{
search(temp);
}
if(choice == 3)
{
takeOut(temp);
}
if(choice == 4)
{
returnBack(temp);
}
if(choice == 5)
{
append(temp);
}
if(choice == 6)
{
cout<<"Sorry you have the privilege needed to use this function."<<endl;
}
if(choice == 7)
{
choice = 0;
}
}
}
My user defined variables get destroyed. I debugged and they just disappeared i am not sure why!
Just in-case its needed here is my add() function because I feel It could be me missing something small or just making a disastrous mistake. My add function is in the functions.cpp and I know all the links are working as I have everything else running apart from this
functions.cpp
Book* append(Book* tempParam)
{
string title;
string author;
string isbn;
bool avail;
cout<<"What is the book called?"<<endl;
cin.clear();
cin.ignore();
getline(cin, title);
cout<<"Who is the author?"<<endl;
cin.clear();
cin.ignore();
getline(cin, author);
cout<<"What is the ISBN to be?"<<endl;
cin>>isbn;
Book* temp = new Book(title, author, isbn, true);
Book* list = tempParam;int count;
while(list!=NULL)
{
if(list->getNext()==NULL&&list->getName()!=title)
{
list->setNext(temp);
temp->setNext(NULL);
temp->setPrev(list);
cout<<"Your book has been added"<<endl;
cout<<temp->getName()<<temp->getAuthor()<<endl;
}
list = list->getNext();
}
tempParam = list;
return tempParam;
}
My user defined classes are working perfectly its just when I go to add that my list gets destroyed any ideas??

*I think the error is found in this section of the code:
list->setNext(temp);
You are "losing" the books because you didn't save them before you change list->next.*
The answer is incorrect because the conditional statement makes sure that it is the last element of the list. Sorry!

Related

update value c++ (singgle linked listed)

i have a question. how to update value in linked listed. I have a code
void edit() {
node *temp;
temp = awal_ptr;
char goldar[5];
int caridata;
int ketemu=0;
if(awal_ptr != NULL) {
cout<<"\n Input Id Yang Akan Diedit\t: ";
cin>>caridata;
while(temp!=NULL) {
temp->id;
if(caridata==temp->id) {
cout<<">>>------------------------------<<<"<<endl;
cout<<" Nama\t: "<<temp->nama<<endl;
cout<<" Golongan Darah\t: "<<temp->gol<<endl;
cout<<" ------------------------------"<<endl;
ketemu=1;
cout<<"Masukan Golongan Darah Baru: ";
cin>>goldar;
temp->id=caridata;
temp->gol==goldar;
//temp = temp->next;
//temp->id=goldar;
cout<<"Data Berhasil Diupdate"<<endl;
} temp=temp->next;
}
if(ketemu==0) {
cout<<" Data tidak ditemukan";
}
} else cout<<" Belum ada data!";
getch();
}
how to update value goldar (lisked list). when i update goldar. no error but value doesnt change. example i update or edit data with id 112 form A to O. the message succes but the value doesnt change it still A. hope you can help me
temp->gol==goldar;
Try = instead of ==. You are comparing values here, not assigning.

How can I repair this error that occurs occasionally when my code is running?

Sometimes the code runs till the end without any errors while other times it stops in the middle and gives me this error Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) here is a picture of it (https://i.stack.imgur.com/uZDX1.png). The error is in my header file named Functions, and the compiler used in this picture is Xcode on a Mac device. I also tried another compiler "Visual Studio" on a Windows device and the code never runs till the end, it always stops in the middle of running and gives me an error in the same line of code, here is a picture of the error Visual Studio gave me Error in Visual Studio.
#include <iostream>
using namespace std;
//products' data
struct products{
int ID;
string Name;
double Price;
int Quantity;
};
//receipt
struct receipt{
string name;
double price;
receipt* link;
};
struct linkedListFunctions{
//inserts node at the end of the list
void insert(receipt** head_name_ref, string new_name, double new_price)
{
receipt* new_name_node = new receipt();
receipt *last = *head_name_ref;
new_name_node->name = new_name;
new_name_node->price = new_price;
new_name_node->link = NULL;
if (*head_name_ref == NULL)
{
*head_name_ref = new_name_node;
return;
}
while (last->link != NULL)//The error is right here
{
last = last->link;
}
last->link = new_name_node;
return;
}
//prints list
void printReceipt(receipt* n){
while(n!=NULL){
cout<<n->name<<": ";
cout<<n->price<<'\t'<<" ";
cout<<endl;
n=n->link;
}
}
//removes first node in the list
receipt* removeFirstreceipt(struct receipt* head)
{
if (head == NULL)
return NULL;
receipt* temp = head;
head = head->link;
delete temp;
return head;
}
};
The first two code boxes are in the header file named Functions.h
The error is in the second code box at line 15, it has a comment next to it
#include "Functions.h"
int main(){
struct products details[5];
details[0] = {0, "Apple Juice", 12, 240};
details[1] = {1,"Bread", 10, 100};
details[2] = {2, "Chocolate", 5, 500};
details[3] = {3, "Dates", 50, 150};
details[4] = {4, "Eggs", 30, 360};
linkedListFunctions list;
//declaring first node in receipt linked list
receipt* head = NULL;
head = new receipt;
//prints all products IDs and Names
for (int i=0; i<5; i++) {
cout<<details[i].ID<<": ";
cout<<details[i].Name<<" ";
cout<<details[i].Price<<"LE"<<endl;
}
char buyAgain;
while ((buyAgain='y' && buyAgain!='n')){
//choosing a product
cout<<"Enter the product's ID to choose it: ";
int chooseProduct;
cin>>chooseProduct;
cout<<"ID: "<<details[chooseProduct].ID<<endl
<<"Name: "<<details[chooseProduct].Name<<endl
<<"Price: "<<details[chooseProduct].Price<<endl
<<"Quantity: "<<details[chooseProduct].Quantity<<endl<<"********"<<endl;
//choosing the quantity
cout<<"How much "<<details[chooseProduct].Name<<" do you want? ";
int chooseQuantity;
cin>>chooseQuantity;
list.insert(&head, details[chooseProduct].Name, details[chooseProduct].Price*chooseQuantity);//
details[chooseProduct].Quantity=details[chooseProduct].Quantity-chooseQuantity;
cout<<details[chooseProduct].Name<<" Left: "<<details[chooseProduct].Quantity<<endl<<"********"<<endl;
cout<<"Would you like to order something else? y=yes n=no";
cin>> buyAgain;
switch(buyAgain) {
case 'y':
break;
case 'n':
//prints receipt
cout<<"***Receipt***"<<endl;
list.printReceipt(head);
}
}
}
The last code box is the main function
this is for sure wrong
char buyAgain;
while ((buyAgain = 'y' && buyAgain != 'n'))
you are attempting to test an uninitialized variable but are in fact assigning to it
2>C:\work\ConsoleApplication1\ConsoleApplication1.cpp(106): warning C4706: assignment within conditional expression
2>C:\work\ConsoleApplication1\ConsoleApplication1.cpp(106): warning C4701: potentially uninitialized local variable 'buyAgain' used
more importantly you do not initialize the fields on receipt, you should have a constructor for it, like this
struct receipt {
string name;
double price;
receipt* link;
receipt() { price = 0; link = nullptr; }
};
For starters these lines:
receipt* head = NULL;
head = new receipt;
do not make a great sense. The operator new creates an uninitialized object of the type receipt (for example the data member link can have an indeterminate value) that is a reason of undefined behavior when the pointer used in functions. What you need is just to write:
receipt* head = NULL;
The condition in this while loop:
while ((buyAgain='y' && buyAgain!='n')){
does not make a sense. buyAgain is always set to 'y' in this sub-expression:
buyAgain='y'
It seems you mean:
while ( buyAgain == 'y' ){
or:
while ( buyAgain != 'n' ){
But before the while loop you have to initialize the variable buyAgain
char buyAgain = 'y';
As the structure receipt is an aggregate then instead of these statements within the function insert:
receipt* new_name_node = new receipt();
new_name_node->name = new_name;
new_name_node->price = new_price;
new_name_node->link = NULL;
you could write:
receipt* new_name_node = new receipt
{
new_name, new_price, nullptr
};
Pay attention to that the functions for processing the list declared in the structure struct linkedListFunctions should be at least static member functions.
The parameter of the function printReceipt should have the qualifier const:
void printReceipt( const receipt* n);
and the output of blanks:
cout<<n->price<<'\t'<<" ";
^^^^^^^^^^^^
in fact has no effect due to the next line
cout<<endl;

How to print the map like a template?

Here is my code:
To understand the code I have to explain a little. First I am getting student and course data from user in different classes. Then in Schedule class I am trying to create a schedule for student. When user enter a valid student and course name I am inserting these datas to another map.
map< string,map<pair<string,int>,pair<string,Array> > > courseScList;
map<pair<string,int>,pair<string,Array> > matchMap;
matchMap map has these datas from another class:
course name,course hours,course day,available hours in this day
These 2 are mine maps and I am using these maps in this code:
void Schedule::studentSchedule() {
string c,s;
int courseNum;
list<string>::iterator studentLoc;
map< string,map<pair<string,int>,pair<string,Array> > >::iterator last;
map<pair<string,int>,pair<string,Array> >::iterator location;
map<pair<string,int>,pair<string ,Array> >::iterator match;
dummy1:
cout<<"Enter the student name"<<endl;
cin >> s;
wrongCourse:
cout<<"Enter the course names you want"<<endl;
cin>>c;
auto predicate = [&](auto& course) { return compareName(course, c); };
studentLoc = find(getStudentList().begin(),getStudentList().end(),s);
location = find_if(getMatchMap().begin(), getMatchMap().end(), predicate);
if(studentLoc != getStudentList().end() || location != getMatchMap().end())
{
getCourseScList().insert(make_pair(s,getMatchMap()));
}
else
{
cout<<"The course or student you wrote isn't available.Please enter existed courses!"<<endl;
goto wrongCourse;
}
cout<<"\n"<<endl;
char dummy;
cout<<"\nDo tou want to create a new schedule?Press y or n."<<endl;
cin>>dummy;
if(dummy == 'Y' || dummy == 'y')
goto dummy1;
else
{
location = last->second.begin();
for(last = getCourseScList().begin();last!=getCourseScList().end();++last)
{
cout<<last->first<<"\t"<<(location->first).first<<"\t"<<(location->second).first<<"\t";
for (const int element : location->second.second)
std::cout << element << " ";
cout<<endl;
++location;
}
}
I am trying to get student and course name from user and if student name and course name in the map I am inserting this to another map. However when I try to print these student,course,day and day hours data I can't see these in same line. I think the wrong code is this:
else
{
cout<<"The course or student you wrote isn't available.Please enter existed courses!"<<endl;
goto wrongCourse;
}
cout<<"\n"<<endl;
char dummy;
cout<<"\nDo tou want to create a new schedule?Press y or n."<<endl;
cin>>dummy;
if(dummy == 'Y' || dummy == 'y')
goto dummy1;
else
{
location = last->second.begin();
for(last = getCourseScList().begin();last!=getCourseScList().end();++last)
{
cout<<last->first<<"\t"<<(location->first).first<<"\t"<<(location->second).first<<"\t";
for (const int element : location->second.second)
std::cout << element << " ";
cout<<endl;
++location;
}
}
With this print loop i can't see the template like this;
Studentname1 -- > Coursename1 ----> Courseday1 -->Coursehours1
Studentname1 -- > Coursename2 ----> Courseday2 -->Coursehours1
Studentname2 -- > Coursename1 ----> Courseday1 -->Coursehours1
Studentname3 -- > Coursename2 ----> Courseday2 -->Coursehours
This is just an example what I want to do. How can I organize the code for it?

if statement is executing,else-if statements are not in java

import javax.swing.JOptionPane;
public class sam{
public static void main(String[]args){
String a;
String b;
int c;
sam s1 = new sam();
a=s1.getInfo();
c=s1.getBalance();
b=s1.getMenu(a,c);
}
//menu method starts here
public String getMenu (String c, Integer d) {
String[] a;
String[] choices = { "Account Balance", "Deposit", "Withdraw", "User Account", "Exit options"};
String input = (String) JOptionPane.showInputDialog(null, "What would you like to do?",
"ATM menu", JOptionPane.QUESTION_MESSAGE, null,choices,choices[0]);
if ((choices[0] == choices[0])){
JOptionPane.showMessageDialog(null,"Your Account Balance is: "+d,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//the if statement is executing properly
else if ((choices[1] == choices[1])){
String in=JOptionPane.showInputDialog("Deposit: ");
int deposit=Integer.parseInt(in);
int add=d+deposit;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+add,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//but when I chose account balance it displays the if statement not the else-if one
else if ((choices[2] == choices[2])){
String in=JOptionPane.showInputDialog("Withdraw: ");
int withdraw=Integer.parseInt(in);
int sub=d+withdraw;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+sub,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[3] == choices[3])){
JOptionPane.showMessageDialog(null," "+c,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[4] == choices[4])){
JOptionPane.showMessageDialog(null,"The program will be terminated in a few seconds","ATM machine",JOptionPane.INFORMATION_MESSAGE);
}
return input;
}
//I'm quite new to programming, I rushed coded it for finals.
All of your if statements will evaluate to true. I think your intentions were to compare String c with each of the Strings in the choices array.
When comparing Strings always use .equals() not ==.
Example:
if (c.equals(choices[0])) {
// code
} else if (c.equals(choices[1])) {
//code
} else if (c.equals(choices[2])) {
// code
}

windows causing breaking point

I am writing a program for a class assignment on learning about pointers and memory management. Allocating memory for student and courses is necessary with the new operator in this assignment and the program seems to run properly but after it prints everything the program crashes and it says that that it has triggered a break point. Any help would be appreciated.
The error is located here but I'm not sure what it means
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Student //Structs
{
string firstName, lastName, aNumber;
double GPA;
};
struct Course
{
int courseNumber, creditHours;
string courseName;
char grade;
};
Student* readStudent(); // Function Prototypes
Course* readCourseArray(int&);
void computeGPA(Student *student, Course *courseArray, int coursesTaken);
void printSummary(Student *studentPTR, Course *courseArray, int courses);
int main() //Main
{
int courses = 0;
Student *studentPTR = readStudent();
Course *coursePTR = readCourseArray(courses);
computeGPA(studentPTR, coursePTR, courses);
printSummary(studentPTR, coursePTR, courses);
delete studentPTR;
delete coursePTR;
system ("pause");
return 0;
}
Student* readStudent() // Read Student
{
Student* student = new Student;
cout<<"\nEnter students first name\n";
cin>>student->firstName;
cout<<"\nEnter students last name\n";
cin>>student->lastName;
cout<<"\nEnter students A-Number\n";
cin>>student->aNumber;
return student;
}
Course* readCourseArray(int &courses) //Read Courses
{
cout<<"\nHow many courses is the student taking?\n";
cin>>courses;
const int *sizePTR = &courses;
Course *coursePTR = new Course[*sizePTR];
for(int count = 0; count < *sizePTR; count++) //Enter course information
{
cout<<"\nEnter student "<<count+1<<"'s course name\n";
cin>>coursePTR[count].courseName;
cout<<"\nEnter student "<<count+1<<"'s course number\n";
cin>>coursePTR[count].courseNumber;
cout<<"\nEnter student "<<count+1<<"'s credit hours\n";
cin>>coursePTR[count].creditHours;
cout<<"\nEnter student "<<count+1<<"'s grade\n";
cin>>coursePTR[count].grade;
}
return coursePTR;
}
void computeGPA(Student *studentPTR, Course *courseArray, int coursesTaken) // Compute GPA
{
double total = 0, hours = 0;
for(int count = 0; count < coursesTaken; count++)
{
hours += courseArray[count].creditHours;
if (courseArray[count].grade == 'A')
total+=4;
else if (courseArray[count].grade == 'B')
total+=3;
else if (courseArray[count].grade == 'C')
total+=2;
else if (courseArray[count].grade == 'D')
total+=1;
else if (courseArray[count].grade == 'F')
total+=0;
}
studentPTR->GPA = (total / hours);
}
void printSummary(Student *studentPTR, Course *courseArray, int courses)
{
cout<<"\nReport\n";
cout<<"\nNumber Name Hours Letter Grade Point Grade";
cout<<"\n------ ---- ----- ------------ -----------\n";
for(int count = 0; count < courses; count++)
cout<<setw(3)<<courseArray[count].courseNumber<<" "<<courseArray[count].courseName<<setw(20)<<" "<<courseArray[count].creditHours<<setw(5)<<" "<<courseArray[count].grade<<endl;
cout<<"\nStudent :"<<studentPTR->firstName<<" "<<studentPTR->lastName;
cout<<"\nA-Number :"<<studentPTR->aNumber;
cout<<"\nOverall GPA :"<<studentPTR->GPA;
}
You're allocating courses with operator new[] (which is for arrays), but freeing it with operator delete, instead of operator delete[].
You should deallocate it like that:
delete[] coursePTR;
I also don't understand why you use the sizePTR pointer instead of directly using courses.
BTW, just so you'd know, this is not a 'find my bug' site. You have a code review site for that.
You need to change
delete coursePTR;
to
delete [] coursePTR;
new always needs to be used with delete, and new [] with delete [], otherwise bad things happen.