对于这个愚蠢的问题,我很抱歉。我有C程序提示用户输入年龄和姓名,然后将年龄和姓名打印到屏幕上。这是我从书中读取的练习。fflush()函数不能使用stdin
此程序:
#include <stdio.h>
int main (void) {
int age;
char name[20];
puts("Enter your age:");
scanf("%d",&age);
fflush(stdin);
puts("Enter your name:");
scanf("%s",name);
printf("Your age is %d\n",age);
printf("Your name is %s\n",name);
return 0;
}
当我输入额外的字符到第一scanf()
程序终止,并分配多余的字符到下一个scanf()
然后,我改变了代码,并添加功能命名为clear_buff()
并使用clear_buff()
中的fgets
函数读取码流中剩余的字符。该代码按我的预期工作。
#include <stdio.h>
#define MAXLEN 80
void clear_buff(void);
int main (void) {
int age;
char name[20];
puts("Enter your age:");
scanf("%d",&age);
clear_buff();
puts("Enter your name:");
scanf("%s",name);
printf("Your age is %d\n",age);
printf("Your name is %s\n",name);
return 0;
}
void clear_buff(void){
char junk[20];
fgets(junk,MAXLEN,stdin);
}
我的问题是为什么fflush(stdin)
不能在此程序中工作?
该书说fflush
函数清除流中的任何缓冲数据。而且我知道 fflush()
函数是C标准函数,如果使用I/O流。
尝试'fflush(stdout)'。 – 2014-10-19 01:27:12
'fflush'用于清除输出。 [见这里](http://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c)了解如何清除输入。 – 2014-10-19 01:29:14
输入流(如stdin)上的'fflush'具有未定义的行为。 – 2014-10-19 01:33:55