[当我编译该程序时,我无法输入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;
}
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/