前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c语言:C语言清空输入缓冲区在标准输入(stdin)情况下的使用

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

作者头像
用户7886150
修改2021-02-14 15:09:43
3K0
修改2021-02-14 15:09:43
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: C++ setbuf()

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

本文系转载,前往查看

如有侵权,请联系?cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系?cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com