您的位置:首页 > 编程语言 > C语言/C++

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

2016-05-29 13:37 881 查看
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为止,此方法可完美清除输入缓冲区,并具备可移植性

本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1720583
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: