我注意到只询问 for 循环中的第一个 scanf ,其余的则跳过 scanf 请求。
int main()
{
int c = 0;
int i;
struct book
{
char name[20];
float price;
int page;
};
printf("\n enter number of book to add\n ");
scanf("%d", &c);
struct book b[c];
printf("\n book details \n ");
for (i = 1; i < c; i++)
{
printf("\n enter name for book %d", i);
scanf(" %c", &b[i].name);
fflush(stdin);
printf("\n enter price for book %d", i);
scanf(" %f", &b[i].price);
fflush(stdin);
printf("\n enter page for book %d", i);
scanf(" %d", &b[i].page);
}
}
输出
enter number of book to add 3
book details enter name for book 1james
enter price for book 1
enter page for book 1
enter name for book 2
enter price for book 2
enter page for book 2
最佳答案
这个:
scanf(" %c",&b[i].name);
看起来非常错误,它读取的单个字符作为名称没有意义,而且也不符合您的用法。
您的意思可能是:
scanf("%19s", b[i].name);
但这也很糟糕,因为 %s
将在空格处停止,而书名可以有多个单词。最好使用 fgets()
获取整行,然后解析它们。
确保在依赖所有 scanf()
调用成功之前检查它们的返回值! I/O 很脆弱,可能会失败。
关于c - For 循环跳过第二个及以后的 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673977/