c語言:C語言清空輸入緩沖區在標準輸入(stdin)情況 -電腦資料

電腦資料 時間:2019-01-01 我要投稿
【www.solarmaxlimited.com - 電腦資料】

    C語言清空輸入緩沖區在標準輸入(stdin)情況下的使用

    程序1:

   

//功能:先輸入一個數字,再輸入一個字符,輸出hello bit#include <stdio.h>int main(){int num = 0;char ch = ' ';scanf("%d", &num);scanf("%c", &ch);printf("hello bit\n");system("pause");return 0;}

    結果:

    7

    hello bit

    請按任意鍵繼續. . .

    分析:并沒有輸入字符,直接就輸出了“hello bit”,因為在點擊回車(‘\n’)時,相當于輸入了一個字符,那么我們需要進行清空緩沖區處理

    程序2:

   

#include <stdio.h>int main(){int num = 0;char ch = ' ';scanf("%d", &num);/*fflush(stdin);*/ //清空緩沖區時容易出錯,不建議使用/*scanf("%*[^\n]");*///也不好用,容易失效    setbuf(stdin, NULL);//使stdin輸入流由默認緩沖區轉為無緩沖區,可以用scanf("%c", &ch);printf("hello bit\n");system("pause");return 0;}

    結果:

    5

    j

    hello bit

    請按任意鍵繼續. . .

    程序3:

   

//功能:先輸入一個數字,再輸入一個字符,輸出hello bit#include <stdio.h>#define CLEAR_BUF()     \int c = 0;          \while ((c = getchar()) != EOF && c != '\n')\{    \   ;               \}int main(){int num = 0;char ch = ' ';scanf("%d", &num);CLEAR_BUF();scanf("%c", &ch);printf("hello bit\n");system("pause");return 0;}

    結果:

    8

    s

    hello bit

    請按任意鍵繼續. . .

    分析:程序3建議使用,不停地使用getchar()獲取緩沖中字符,直到獲取的C是“\n”或文件結尾符EOF為止,此方法可完美清除輸入緩沖區,并具備可移植性

最新文章
国产v亚洲v天堂无码网站,综合亚洲欧美日韩一区二区,精品一级毛片A久久久久,欧美一级待黄大片视频
亚洲另类日韩国产综合 | 免费国内精品久久久久影院 | 在线看片亚洲免费 | 亚洲天堂精品在线 | 最新国产资源片在线观看 | 亚洲欧美精品专区精品 |