首页 > 解决方案 > 如何让每个 scanf 工作而不跳过

问题描述

我用gets和scanf做循环。实际上我为换行缓冲区腾出了空间。所以我认为每个 scanf 都有效,但是当我向 &books[ctr].cost 编译器输入值时,会跳过接下来的 3 个问题。我不知道为什么它这样工作

书籍是结构变量

for (ctr = 0 ; ctr < 3 ; ctr++)
{
    printf("What is the name of the book #%d?\n", (ctr+1));
    gets(books[ctr].title);
    puts("Who is the author?  ");
    gets(books[ctr]. author);
    puts("How much did the book cost?  ");
    scanf("  $%f", &books[ctr].price);
    puts("How many pages in the book?  ");
    scanf("  %d", &books[ctr].pages);
    getchar( );
}
printf("\n\n Here is the collection of books : \n");
for (ctr = 0 ; ctr < 3 ; ctr ++)
{
    printf("#%d: %s by %s", (ctr+1), books[ctr].title, books[ctr].author);
    printf("\n It is %d pages and costs $%.2f", books[ctr].pages, books[ctr].price);
    printf("\n\n");
}

return 0;

}

标签: cfor-loopstructscanf

解决方案


首先,有两个建议:

用于fgets()获取用户输入,然后使用sscanf().


推荐阅读