【发布时间】:2020-06-07 22:01:11
【问题描述】:
我需要在列表末尾添加新项目,删除最后一项并显示整个列表。 在显示整个列表时,由于某种原因,仅显示堆栈的最后一个元素,按列表中的元素数量计算。 为什么?
#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;
}
}
}
【问题讨论】:
-
使用调试器逐行遍历它或在循环中打印有趣的值。当它开始行为不端时,你会得到一个线索。
标签: c++ class dynamic-memory-allocation construct ctor-initializer