fflush使用
頭文件:#include<stdio.h>
定義函數:int fflush(FILE * stream);
函數說明:fflush()會強迫將緩沖區內的數據寫回參數stream指定的文件中,如果參數stream為NULL,fflush()會將所有打開的文件數據更新。
返回值:成功返回0,失敗返回EOF,錯誤代碼存于errno中。
fflush()也可用于標準輸入(stdin)和標準輸出(stdout),用來清空標準輸入輸出緩沖區。
stdin是standard input的縮寫,即標準輸入,一般是指鍵盤;標準輸入緩沖區即是用來暫存從鍵盤輸入的內容的緩沖區。stdout是standard output 的縮寫,即標準輸出,一般是指顯示器;標準輸出緩沖區即是用來暫存將要顯示的內容的緩沖區。
代碼一
?
#include "stdafx.h" #include<stdlib.h> #include<stdio.h>#pragma warning(disable:4996)using namespace std;int _tmain(int argc, _TCHAR* argv[]) {int a;char c;scanf("%d", &a);c = getchar();printf("a=%d,c=%c", a, c);return 0; }
?
代碼二
?
#include "stdafx.h" #include<stdlib.h> #include<stdio.h>#pragma warning(disable:4996)using namespace std;int _tmain(int argc, _TCHAR* argv[]) {int a;char c;scanf("%d", &a);fflush(stdin);c = getchar();printf("a=%d,c=%c", a, c);return 0; }
?
對比上面的代碼,代碼一沒有清空輸入緩沖區,回車時,將123賦值給a,緩沖區剩下abc,接著執行getchar(),發現緩沖區有內容,就無需等待用戶輸入,直接讀取了,將'a'賦給c。代碼二執行到fflush(),清空緩沖區,getchar()發現緩沖區沒有內容,需要等待用戶輸入,所以必須輸入兩次。
總結
- 上一篇: c语言键盘按f1显示f1,windows
- 下一篇: MPI 集合通信函数 MPI_Reduc