为什么我不能输入第二本书的书名?

问题描述 投票:-1回答:1

[当我编译该程序时,我无法输入book2.title名称,使用获取功能是错误的,为什么?请进一步解释.......................................

#include<stdio.h>
#include<string.h>
struct name{
char author[20];
char title[20];
float price;
};
int main()
{
    struct name book1,book2;
    printf("Enter 1st title name:");
    gets(book1.title);
    printf("Enter 1st Author name:");
    gets(book1.author);
    printf("Enter 1st Book price:");
    scanf("%f",&book1.price);
    printf("\nThe 1st Book Name is %s",book1.title);
    printf("\nThe 1st Book Author is %s",book1.author);
    printf("\nThe 1st Book Price is %f",book1.price);
    printf("\nEnter 2nd title name:");
    gets(book2.title);
    printf("Enter 2nd Author name:");
    gets(book2.author);
    printf("Enter 2nd Book price:");
    scanf("%f",&book2.price);

    printf("\nThe 2nd Book Name is %s",book2.title);
    printf("\nThe 2nd Book Author is %s",book2.author);
    printf("\nThe 2nd Book Price is %f",book2.title);
     return 0;


}


c structure
1个回答
0
投票
忽略代码中的错误,您要问的问题在于这两行:

scanf("%f",&book1.price); ... gets(book2.title);

注意,当您在终端中输入book1的价格(例如12.3)时,随后请按Enter。因此,stdin缓冲区包含字符12.3\n。 scanf读取它可以解释为浮点数12.3的前几个字节,而保留了\n的缓冲区。现在,当您运行gets时,它将读取换行符,并且第二本书的标题为空白字符串“ \ 0”。

查看此网站:https://www.geeksforgeeks.org/problem-with-scanf-when-there-is-fgetsgetsscanf-after-it/

© www.soinside.com 2019 - 2024. All rights reserved.