【发布时间】:2022-01-21 11:11:57
【问题描述】:
我正在使用 C++ 中的字符数组编写堆栈示例。 运行程序时,它显示 3 个选项。第 1 用于推送,第 2 用于弹出,第 3 用于输出。 我不知道当我将字符推入字符串时,我无法弹出最高值。
#include <iostream>
int top = -1;
char stack[10];
int n = 10;
using namespace std;
char push()
{
string a;
if (top == n - 1) {
cout << "stack is full" << endl
<< endl;
}
else
cout << "enter value to push" << endl;
cin >> a;
// loop
for (int i = 0; i < a.length(); i++) {
stack[top] = a[i];
top = top + 1;
}
for (int i = top; i >= -1; i--) {
cout << " " << stack[i] << endl;
}
return top;
}
char pop()
{
char x;
// int l;
// cin>>l;
if (top < 0) {
cout << "stack is empty" << endl;
return 0;
}
else
for (int i = n; i > -1; i--) {
stack[top] = x;
--top;
}
}
int main()
{
int choose;
do {
cout << endl;
cout << "choose your option" << endl;
cout << "1 for push" << endl;
cout << "2 for pop" << endl;
cout << "3 for print" << endl;
cout << "-1 for exit" << endl;
cin >> choose;
switch (choose) {
case (1): {
push();
break;
}
case (2): {
pop();
} break;
case (3): {
if (top >= 0) {
cout << "All values in the Stack are " << endl;
for (int i = top; i >= -1; i--) {
cout << stack[i] << endl;
}
}
} break;
}
} while (choose != -1);
return 0;
}
我不知道为什么我不能从字符堆栈中弹出元素。 我正在尝试,但我无法弄清楚我的代码有什么问题。一点帮助将不胜感激。
【问题讨论】:
-
pop 既不是弹出(它根据不完整的比较将某些内容分配给顶部)也不是返回值。我很惊讶您没有收到最后一个编译器警告,或者是吗? (您应该始终修复所有编译器警告,而不仅仅是错误)。总而言之,您的代码仍然很乱,甚至可能无法编译
-
if ( l == )应该被编译器拒绝。for (int i = top; i >= -1; i--)表示 -1 将用于索引数组。在循环中执行top = top+1;(++top) 而不测试每次迭代是否溢出是错误的。 -
第一次运行时:
stack[top]=a[i];is not top 等于 -1?