gpt4 book ai didi

Case 标签不会缩减为 C 中的整数常量?

转载 作者:行者123 更新时间:2023-12-04 11:39:35 24 4
gpt4 key购买 nike

我正在开发一个游戏,我运行我的代码并收到错误“case label does not reduce to an integer constant”。我想我知道这意味着什么,但我该如何解决呢?这是我的代码:

#include<stdio.h>
#include<stdlib.h

int player_cash[3] = {50};
char job[][20] {
'A',
'B',
'C',
"Donate",
"Go to work",
"Exit"
};
int jobs;

int main()
{
while(player_cash[0] > 0) {
printf("Please type A, B, C, Donate, Go to work, or Exit\n");
switch(jobs) {

case 'A':
player_cash[0]-=5;
player_cash[1]+=5;
printf("Cash=%i\n\n", player_cash[0]);
continue;

case 'B':
player_cash[0]-=5;
player_cash[2]+=5;
printf("Cash=%i\n\n", player_cash[0]);
continue;

case 'C':
player_cash[0]-=5;
player_cash[3]+=5;
printf("Cash=%i\n\n", player_cash[0]);
continue;

case "Donate":
player_cash[0]-=15; //Error here
player_cash[1]+=5;
player_cash[2]+=5;
player_cash[3]+=5;
printf("Cash donated\n\n");
printf("Cash=%i\n\n", player_cash[0]);
continue;

case "Go to work":
player_cash[0]+=10; //Error here
printf("Work done\n\n");
printf("Cash=%i\n\n", player_cash[0]);
continue;

case "Exit":
printf("Thanks for playing!\n\n"); //Error here
break;

default:
printf("Does not compute");
continue;
}
}
getchar();
return 0;
}

所以,我希望用户做的是输入其中一个选项,然后执行与之对应的操作。我该如何解决这个问题?

最佳答案

您不能将字符串用作 case 表达式:

case "Donate":

只能使用整数表达式,例如case 'A': 没问题。

概念上你有问题:jobs 是一个 int,而你正在测试字符串。如果你想让用户输入字符串(超过一个字符),你需要保留一个字符串变量,并使用类似 fgets 的东西来获取整行输入。

关于Case 标签不会缩减为 C 中的整数常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12874960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com