C語言清除輸入緩衝區【轉】
阿新 • • 發佈:2019-02-17
在使用scanf輸入時,如果輸入不合法,此時可以檢查其返回值為0,但下次再呼叫時,上次不合法的輸入,還在輸入緩衝區中,此時就會接著不合法,如下:
- #include <stdio.h>
- int main(int argc,char** argv){
- int id ;
- int ret = scanf("%d",&id);
- while(ret == 0){
- ret = scanf("%d",&id);
- printf("input failed\n");
- }
- printf("you input is %d\n",id);
- return 0;
- }
有這麼幾種方法,可以解決這個問題
一,使用setbuf
功 能: 把緩衝區與流相聯
用 法: void setbuf(FILE *steam, char *buf);
說明:setbuf函式具有開啟和關閉緩衝機制。為了帶緩衝進行I/O,引數buf必須指向一個長度為BUFSIZ(定義在stdio.h標頭檔案中)的緩衝區。通常在此之後該流就是全緩衝的,但是如果該流與一個終端裝置相關,那麼某些系統也可以將其設定為行緩衝。為了關閉緩衝,可以將buf引數設定為NULL。
- #include <stdio.h>
- int main(int argc,char** argv){
- int id ;
- int ret = scanf("%d",&id);
- while(ret == 0){
- printf("input failed\n");
- setbuf(stdin,NULL);
- ret = scanf("%d",&id);
- }
- printf("you input is %d\n",id);
- return 0;
- }
- #include <stdio.h>
- int main(int argc,char** argv){
- int id ;
- int ret = scanf("%d",&id);
- while(ret == 0){
- printf("input failed\n");
- // setbuf(stdin,NULL); 1
- __fpurge(stdin);
- ret = scanf("%d",&id);
- }
- printf("you input is %d\n",id);
- return 0;
- }
如果提示沒有找到這個函式的話,則需要包含#include <stdio_ext.h>
三,把緩衝區全讀完
- #include <stdio.h>
- int main(int argc,char** argv){
- int id ;
- char c ;
- int ret = scanf("%d",&id);
- while(ret == 0){
- printf("input failed\n");
- // setbuf(stdin,NULL); 1
- // __fpurge(stdin);
- //
- do{
- c = getchar();
- }while(c != '\n' && c != EOF);
- ret = scanf("%d",&id);
- }
- printf("you input is %d\n",id);
- return 0;
- }
經過測試,上面的方法都可以實現目的。