我们什么时候需要清除 scanf 缓冲区?

When do we need to clear the scanf buffer?

我一直以为“'\n' in buffer”的问题只有在读字符的时候才会出现, 但是,我通过以下代码偶然发现了这个问题:

int main(int argc, char** argv){
    int height = 0, width = 0;

    while(height < 1 || height > 10|| width < 1 || width > 15){
        printf("Please insert the height(1~10) and width(1~15) of the parallelogram (integers): ");
        if(scanf("%d %d", &height, &width) != 2){
            height = width = 0;
        }
    }
    return 0;
}

如上所述,我只用 scanf 读取整数, 但是当我输入无效的东西时,这段代码仍然陷入无限循环。 如果我清理缓冲区就解决了。

所以我的问题是,这个“'\n' in buffer”问题是普遍现象吗? 还是仅在特殊用途时才会发生? 如果它只发生在特殊用途上,我是否需要遵循一些一般准则?

一般准则是不使用*scanf() 进行用户输入。您从格式错误的输入中正常恢复的能力太有限,错误的可能性太高(从 SO 上大量的 *scanf() 相关问题可以看出)。 *scanf() 函数系列最适合仅用于读取格式正确的输入(即之前由您自己的应用程序写入的数据)。

无论如何,用户输入都是基于行的,至少在您依赖标准输入功能时是这样。

因此 使用 fgets() to read a full line of input, then parse it in-memory. Functions like strtol() or strtod() can give very specific feedback at which point exactly they stopped parsing, you can skip back and try a different parse, you have all the string-handling functions 的标准来区分用户的输入。如果事情变得不顺利,您可以在错误消息中重复整行输入,添加您喜欢的有关解析尝试的任何信息。