首页 > 解决方案 > 一种推荐的刷新标准输入缓冲区的方法

问题描述

通过从用户那里获取输入,如果用户输入超出限制的任何内容,程序将只使用从开始到限制的输入。

但是,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

解决方案


推荐阅读