c语言:C语言清空输入缓冲区在标准输入(stdin)情况下的使用

来源:互联网 发布:淘宝内部优惠券 赚佣金 编辑:程序博客网 时间:2024/05/17 09:01

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(stdinNULL);//使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为止,此方法可完美清除输入缓冲区,并具备可移植性


本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1720583

0 0
原创粉丝点击