對於這個愚蠢的問題,我很抱歉。我有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