我现在正在学习堆栈,我决定尝试从万智牌聚集规则中制作一个涉及堆栈的小程序,该程序也遵循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 OVERFLOWn");
return;
}
st->top++;
strcpy(st->item[st->top], value);
}
char pop(stack* st) {
if (st->top == -1) {
printf("STACK UNDERFLOWn");
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?nn");
printf("1. Cast a spelln2. Resolve the next spelln3. Pass prioritynn");
while (1) {
scanf("%d", &choice);
switch (choice) {
case 1:
printf("What is the spell?nn");
scanf("%[^n]s", val);
printf("%s", val);
push(&st1, val);
case 2:
strcpy(val, pop(&st1));
printf("%s resolves.nn", val);
case 3:
exit(0);
}
}
return 0;
}
您会收到错误的原因是由于类型转换。
char pop(stack* st) {
if (st->top == -1) {
printf("STACK UNDERFLOWn");
return -1;
}
char value;
strcpy(value, st->item[st->top]);
st->top--;
return value;
}
第一件事,在处理数组时不需要传递地址。另一件事是您尝试将整个字符串复制到单个字符变量中。因此,代码中存在很多类型转换问题。
我建议您制作 void 数据类型的函数,并在函数块中提供功能。只需调用带有 top 值的 pop 函数作为参数,然后在要弹出的函数中打印字符串。堆栈是一种零阶数据结构,因此不需要输入即可弹出。