我现在正在学习堆栈,我决定尝试制作一个涉及 Magic the Gathering 规则中的堆栈的小程序,该程序也遵循 LIFO 顺序。
用户询问是否愿意
- 施展咒语(推)
- 解决咒语(弹出)或
- 退出。
现在棘手的部分是我试图允许堆栈的元素每个都是多个单词。这引起了很多问题。
我可以输入一个单词并将其打印在 while(1)
循环之外,但如果我将它放在里面,一切都会变得困惑。有什么想法吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
typedef struct {
char item[SIZE];
int top;
} stack;
void init(stack*);
void push(stack*, char[]);
char pop(stack*);
void init(stack* st) {
st->top = -1;
}
void push(stack* st, char* value) {
if (st->top == SIZE - 1) {
printf("STACK OVERFLOW\n");
return;
}
st->top++;
strcpy(st->item[st->top], value);
}
char pop(stack* st) {
if (st->top == -1) {
printf("STACK UNDERFLOW\n");
return -1;
}
char value;
strcpy(value, st->item[st->top]);
st->top--;
return value;
}
int main() {
stack st1, st2;
int choice;
char val[20];
init(&st1);
init(&st2);
printf("You have priority. What would you like to do?\n\n");
printf("1. Cast a spell\n2. Resolve the next spell\n3. Pass priority\n\n");
while (1) {
scanf("%d", &choice);
switch (choice) {
case 1:
printf("What is the spell?\n\n");
scanf("%[^\n]s", val);
printf("%s", val);
push(&st1, val);
case 2:
strcpy(val, pop(&st1));
printf("%s resolves.\n\n", val);
case 3:
exit(0);
}
}
return 0;
}
最佳答案
您收到错误的原因是类型转换。
char pop(stack* st) {
if (st->top == -1) {
printf("STACK UNDERFLOW\n");
return -1;
}
char value;
strcpy(value, st->item[st->top]);
st->top--;
return value;
}
首先,处理数组时不需要传递地址。另一件事是您试图将整个字符串复制到单个字符变量中。所以,你的代码中存在很多类型转换问题。
我建议您将函数设为void数据类型,并在函数 block 内提供功能。只需使用 top 值作为参数调用 pop 函数,并在要弹出的函数中打印字符串。 堆栈是零阶数据结构,因此不需要用于弹出目的的输入。
关于c - 简单的堆栈程序不接受输入并崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56650957/