gpt4 book ai didi

C 编程尝试在 scanf 中获取枚举字并将其放入 int 数组中

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

我尝试运行这个程序并使用枚举从用户那里获取一个字符串并将其作为 int 放入 A 数组中问题是,当我尝试使用 scanf 从用户那里获取数据时,而不是通过其命令向前运行程序

这是代码:

#include <stdio.h>
#include <string.h>


int main()
{
enum color { RED = 1, BLUE, BLACK };
char choice[6];
int colors[21];
int i, counter_red = 0, counter_blue = 0, counter_black = 0, x;


for (i = 0; i < 20; i++)
{
printf("Write your favorite color : RED, BLUE or BLACK\n");
scanf_s("%s", &choice);


if (strcmp(choice, "BLACK") == 0)
{
colors[i] = 3;
}

if (strcmp(choice, "BLUE") == 0)
{
colors[i] = 2;
}

if (strcmp(choice, "RED") == 0)
{
colors[i] = 1;
}



}


for (x = 0; x < 20; x++)
{
if (colors[x] == 1)
{
counter_red++;
}
else if (colors[x] == 2)
{
counter_blue++;
}
else if (colors[x] == 3)
{
counter_black++;
}
}
if (counter_red > counter_blue && counter_red > counter_black)
{
printf("%s", "The most popular color is: RED\n");
}
else if (counter_blue > counter_red && counter_blue > counter_black)
{
printf("%s", "The most popular color is: BLUE\n");
}
else if (counter_black > counter_red && counter_blue < counter_black)
{
printf("%s", "The most popular color is: BLACK\n");
}
printf("RED: %d % \nBLUE: %d %\nBLACK : %d % \n", counter_red * 5, counter_blue * 5, counter_black * 5);


return 0;

}

最佳答案

您正在使用scanf_s错误的。首先,当将数组choice传递给函数时,它会衰减为指针,因此您不应该在那里使用地址运算符&。其次,更重要的是,对于格式字符串中的每个格式代码,scanf_s需要两个参数:转换的目标以及目标的大小。

由于您没有传递大小,因此您有 undefined behaviorscanf_s 函数尝试获取堆栈的该值时。

您的通话应该如下所示

scanf_s("%s", choice, sizeof(choice));
<小时/>

顺便说一句:您实际上并没有使用您定义的枚举。要使用它,您应该执行以下操作:

...
enum color colors[20];
...
colors[i] = RED;

作为另一个旁注:您仅在 colors 数组中使用 20 个条目,但您将其定义为 21 个条目。

关于C 编程尝试在 scanf 中获取枚举字并将其放入 int 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28062693/

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