c - 一种推荐的刷新标准输入缓冲区的方法
问题描述
通过从用户那里获取输入,如果用户输入超出限制的任何内容,程序将只使用从开始到限制的输入。
但是,fgets
再次使用将读取相同的字符串,这可能是不希望的。
因为不建议在标准输入上使用fflush
,并且某些操作系统不会表现类似或不允许这样做,所以有没有在不终止程序的情况下清除标准输入缓冲区的常规方法?
这是一个示例片段:
#include <stdio.h>
#include <string.h>
int main(void)
{
printf("Input anything less than 10 characters\n");
char str[10];
while (1)
{
//fgets the first 10 characters of the input and ignore anything after the first 10 characters
char input[10];
fgets(input, 10, stdin);
//when the user inputs more than 10 characters, the program will ignore the rest of the input
if (strlen(input) > 10)
{
continue;
}
//print the input
printf("%s\n", input);
break;
}
fgets(str, 10, stdin);
printf("%s\n", str);
return 0;
}
编辑:
我查看了围绕该主题的其他答案,虽然
while ((c = getchar()) != '\n') ;
可能有助于解决这个问题,但我希望采用一种不一定依赖循环的传统方式。
解决方案
推荐阅读
- c# - WPF 使用服务参考,但我无法获得授权的服务客户端
- jquery - Laravel - 如何对多个日期使用验证
- c++ - 如何启用 std::experimental::atomic_shared_pointer
- python - 尝试使用python控制游戏
- laravel - 未找到 Laravel 5.8 类“表单”
- c# - 用于存储长类型的 C# 快捷方式?
- gridview - 从 javascript 或 jquery 中清除 gridview 数据
- javascript - Chrome扩展中的VueJS多个页面
- c# - DM Join 消息在 Discord C# Bot 中不起作用
- asp.net-core-mvc - User.Identity.IsAuthenticated = false 登录成功后使用 web api mvc core 3.0