I need to add new items to the end of the list, delete the last one and display the entire list. When displaying the entire list, for some reason, only the last elements of the stack are displayed, by the number of elements in the list. Why?
#include <iostream>
#include <stdio.h>
#include <stack>
using namespace std;
struct Node
{
char* name = new char[6];
float sumary;
int amount;
Node(char* name, float sumary, int amount) :name(name), sumary(sumary), amount(amount)
{
}
Node() {}
};
int main()
{
int command;
stack<Node> node;
for (;;)
{
printf("Input command:\n 1 - add,\n 2 - delete last,\n 3 - show all,\n 4 - exit\n");
scanf("%d", &command);
switch (command)
{
case 1:
char name[6];
float sumary;
int amount;
printf("Enter name: ");
scanf("%s", &name);
printf("Enter sumary: ");
scanf("%f", &sumary);
printf("Enter amount: ");
scanf("%d", &amount);
node.push(Node(name, sumary, amount));
break;
case 2:
node.pop();
printf("The last have been deleted");
break;
case 3:
while (!node.empty())
{
Node temp = node.top();
node.pop();
cout << temp.name << " " << temp.sumary << " " << temp.amount << endl;
}
break;
case 4:
return 0;
default:
printf("Wrong command...");
break;
}
}
}
In the constructor
:name(name)does not do what you expect while name is achar*, you do not deeply copy the name but just save the pointer which become invalid out of theswitchwith an undefined behavior (and lost the allocated array ofcharproducing a memory leak).Use a
std::stringrather than achar*and you will have the expected behavior. That also simplify a lot the management when a Node is copied, assigned, deleted because you have nothing to do, which is not the case using a pointer.Out of that having
char name[6];if a word having more than 5 characters is available forscanf("%s", &name);it writes out of your array with an undefined behavior.You do not also check the calls of
scanfsuccess checking they return 1, you are not protected if an input is invalid.Note rather than to use C functions to read/write you can use iostream features (also checking the readings success anyway).
The choice of a
std::stackrather than for instance astd::vectoris strange because to write its content is less practical.A way to do can be where the stack is not emptied when writing its contains :
Compilation and execution :
It can be also a good idea to define the
operator<<in Node rather than to put its members public to be able to access them in main to write them