我有以下C代码。
#include<stdio.h>
int main()
{
//Declaring structure book.
struct book
{
char name;
float price;
int pages;
};
struct book b[5];
int i;
//Below loop takes the info if 5 books from user
for (i=0; i<5; i++)
{
printf("Enter name, price, and pages: ");
fflush( stdin );
scanf("%c%f%d",&b[i].name,&b[i].price,&b[i].pages);
}
return 0;
}
但是,当我编译并运行时,会发生一些奇怪的事情。
-bash-4.1$ ./a.out
Enter name, price, and pages: A 23 34
Enter name, price, and pages: B 34 54
Enter name, price, and pages: Enter name, price, and pages: C 56 78
Enter name, price, and pages: -bash-4.1$
您可以看到,当 i = 2 时,scanf() 不会等待键盘。然后当 i = 3 时,scanf() 等待键盘输入。同样在 i=4 中,scanf() 不等待键盘输入。
我想我用过
fflush(stdin);
在正确的地方。我不希望返回键在下一个 scanf() 的缓冲区中。
为了调试,我尝试不使用 fflush(stdin) 并查看发生了什么。但即使没有 fflush(stdin),当我运行程序时也会发生同样的事情。所以我猜 fflush(stdin) 不会导致这个问题。
请任何人指出,我的程序哪里出错了?
谢谢。