gpt4 book ai didi

c - scanf 在 C 中捕获带有\0 和一串零的 char 类型字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:38 25 4
gpt4 key购买 nike

我正在处理 C 中的枚举,但无法在以下示例中找到问题的根源,即输出始终是“抱歉!”:

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

typedef enum
{
summer, winter, fall, spring
} season;
void printPhrase (season s);

int main(void)
{
printf("What's your prefered season? ");
char seasonHold[10], seasonHold2[10];
scanf("%s", seasonHold);
for (int n = 0; n < strlen(seasonHold); n++)
{
if (n != '\0')
seasonHold2[n] = seasonHold[n];
}
printPhrase (*seasonHold2);
return 0;
}

void printPhrase (season s)
{
if (s == summer)
printf("It's hot out!\n");
else if (s == fall)
printf("It's getting cooler!\n");
else if (s == winter)
printf("Should be really cold!\n");
else if (s == spring)
printf("It should be lovely outside!\n");
else
printf("Sorry!\n");
}

问题是无论我输入什么,总是有一个输出:对不起!谢谢。


此外,这可以解决问题:我可以通过将主要功能更改为以下内容来管理它:

int main(void)
{
printf("What's your prefered season? ");
char seasonHold[10];
scanf("%s", seasonHold);
if (seasonHold[0] == 's')
printPhrase (summer);
else if (seasonHold[0] == 'f')
printPhrase(fall);
else if (seasonHold[1] == 'p')
printPhrase(spring);
else if (seasonHold[0] == 'w')
printPhrase(winter);
return 0;
}

最佳答案

枚举就像常数整数。这里:夏天=0,冬天=1,...

seansonhold 是一个 char*。通过取消引用它你得到一个字符。然后这个 char 将被转换为 'season' 类型,因为 char->int 不会给出编译器错误。

所以你基本上在这里测试你的 char 数组的第一个字节是否等于 0,1,2..

关于c - scanf 在 C 中捕获带有\0 和一串零的 char 类型字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706176/

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