gpt4 book ai didi

c - C 语言中的结构

转载 作者:太空宇宙 更新时间:2023-11-04 05:40:26 26 4
gpt4 key购买 nike

什么是错误?我在我的代码中找不到任何错误,但它没有正确接受输入,它还显示了一些垃圾值。谢谢:

int main()
{
struct book
{
char name;
int price;
int pages;
};
struct book b[5];
int i;

for (i = 0; i < 5; i++)
{
printf("enter name price pages\n");
scanf("%c", &b[i].name);
scanf("%d", &b[i].price);
scanf("%d", &b[i].pages);
}
for (i = 0; i < 5; i++)
printf("%c %d %d\n", b[i].name, b[i].price, b[i].pages);
return 0;
}

最佳答案

大多数书的名字都比一个字母长。

您需要相应地调整结构:

enum { MAX_BOOKNAMELEN = 32 }; // Probably too short

struct book
{
char name[MAX_BOOKNAMELEN];
int price;
int pages;
};

您还需要调整输入:

    if (scanf("%31[^\n]", b[i].name) != 1)
...report error; do not use this book entry...

'31'是凭空变出来的;它比 MAX_BOOKNAMELEN 少一。请注意,书名经常包含空格;因此 %s 跳过前导空格并在一个或多个非空格字符后停在第一个空格处不适合阅读标题。创建格式字符串的一种方法是通过 sprintf() — 如果 MAX_BOOKNAMELEN 改变大小,这将适应:

char name_fmt[16];
snprintf(name_fmt, sizeof(name_fmt), "%%%d[^\n]", MAX_BOOKNAMELEN-1);

if (scanf(name_fmt, b[i].name) != 1)
...error...

更彻底的修订可能会使用 fgets()sscanf() 或其他工具,而不是直接调用 scanf()

关于c - C 语言中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428556/

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