【发布时间】:2019-06-18 14:02:42
【问题描述】:
我现在正在学习堆栈,我决定尝试制作一个涉及 Magic the Gathering 规则中的堆栈的小程序,它也遵循 LIFO 顺序。
用户询问是否愿意
- 施法(推)
- 解决一个咒语(pop)或
- 退出。
现在棘手的部分是我试图让堆栈的元素每个都是多个单词。这导致了很多问题。
我可以输入一个单词并在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;
}
【问题讨论】:
-
你用错了标签——那不是c#代码
-
您可能想要移动用作 while 循环内菜单的前两个
printfs。此外,pop返回单个char而不是字符串。 -
好吧,你应该启用编译器警告,它会告诉你一些问题:你在
pop函数中混合了char和char*。实际上,您的堆栈只能存储 20 个字符,但似乎您想在其中存储单词...您应该问自己:堆栈中需要存储多少个单词(咒语),最大是多少咒语的大小? -
“一切都乱了套”的信息量不是很大。和“有什么想法吗?”不是一个特别有用的问题。您知道您编写的代码中发生了什么吗?如果你这样做,然后用文字描述问题。如果您不这样做,那么请花一些时间调查您的代码在做什么,以便您有一个特定的问题。当您没有告诉我们您想要做什么时,期望我们查看您的代码并弄清楚为什么它没有按照您想要的方式做......是不合理的。