自拍无码在线|亚洲AvAv国产|手机久草视频在线|国产三区四区视频|日夲強伦一级入口|欧美香蕉视频一区二区|亚洲涩图日本五月|最新免费成人网址|超碰91官网在线观看|国产口爆在线观看

c語言:C語言清空輸入緩沖區(qū)在標(biāo)準(zhǔn)輸入(stdin)情況 -電腦資料

電腦資料 時(shí)間:2019-01-01 我要投稿
【www.zwdianwu.cn - 電腦資料】

    C語言清空輸入緩沖區(qū)在標(biāo)準(zhǔn)輸入(stdin)情況下的使用

    程序1:

   

//功能:先輸入一個(gè)數(shù)字,再輸入一個(gè)字符,輸出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;}

    結(jié)果:

    7

    hello bit

    請(qǐng)按任意鍵繼續(xù). . .

    分析:并沒有輸入字符,直接就輸出了“hello bit”,因?yàn)樵邳c(diǎn)擊回車(‘\n’)時(shí),相當(dāng)于輸入了一個(gè)字符,那么我們需要進(jìn)行清空緩沖區(qū)處理

    程序2:

   

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

    結(jié)果:

    5

    j

    hello bit

    請(qǐng)按任意鍵繼續(xù). . .

    程序3:

   

//功能:先輸入一個(gè)數(shù)字,再輸入一個(gè)字符,輸出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;}

    結(jié)果:

    8

    s

    hello bit

    請(qǐng)按任意鍵繼續(xù). . .

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

最新文章