本文介绍了为什么&;t scanf()不等待键盘输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下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);
放在正确的位置。我不希望Return键在下一个scanf()的缓冲区中。
为了调试,我尽量不使用fflush(Stdin),看看会发生什么。但是,即使没有fflush(Stdin),当我运行程序时也会发生同样的事情。所以我猜fflush(Stdin)不是导致这个问题的原因。
请谁指出我的程序出了什么问题?
谢谢。
推荐答案
C11标准解释了%c
的工作原理:
因此,Enter键生成的换行符由%c使用。您可以通过在%c
前添加空格来修复此问题:
您的代码变为scanf(" %c%f%d",&b[i].name,&b[i].price,&b[i].pages);
。
请注意,此处不应使用fflush
。
这篇关于为什么&;t scanf()不等待键盘输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!