c - For 循环跳过第二个及以后的 scanf

标签 c

我注意到只询问 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/

相关文章:

c - 如何使用 fgets 和 printf ("%s")读取并打印结果数组?

c - 按执行顺序列出函数

c - 将时间信息从 NTP 服务器传递到 strftime 函数

C - 使 msgrcv 与信号共存

c - Win32 控制台应用程序中的对话框和小部件库(C 语言)

c - 段错误和 realloc() : invalid next size:

c - 试图退出阻塞的 UDP 套接字读取

c - mingw64 系统 ("command") 与 shell 中的 "command"不同

c - 尽管指针已初始化,但出现神秘的段错误

c - c编程语言中的宏评估