Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 什么时候需要清除扫描缓冲区?_C_Scanf - Fatal编程技术网

C 什么时候需要清除扫描缓冲区?

C 什么时候需要清除扫描缓冲区?,c,scanf,C,Scanf,我一直认为只有在读取字符时才会出现“'\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 w

我一直认为只有在读取字符时才会出现“'\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;
}
int main(int argc,char**argv){
整数高度=0,宽度=0;
而(高度<1 | |高度>10 | |宽度<1 | |宽度>15){
printf(“请插入平行四边形(整数)的高度(1~10)和宽度(1~15):”;
如果(扫描频率(“%d%d”、&高度和宽度)!=2){
高度=宽度=0;
}
}
返回0;
}
如上所述,我只使用scanf读取整数, 但当我输入一些无效的东西时,这段代码仍然卡在一个无限循环中。 如果我清除缓冲区,它是固定的

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

一般准则是不要使用
*scanf()
进行用户输入。您从格式不正确的输入中优雅地恢复的能力太有限,出错的可能性太高(从这里大量的
*scanf()
-相关问题可以看出)。
*scanf()
函数系列最好仅用于读取格式良好的输入(即以前由您自己的应用程序编写的数据)

不管怎样,用户输入都是基于行的,至少如果您依赖于标准输入函数的话


因此用于读取整行输入,然后在内存中解析它。像or这样的函数可以给出非常具体的反馈,在什么时候它们停止了解析,您可以跳回去尝试不同的解析,您可以使用所有的标准来区分用户的输入。如果事情变成梨形,您可以在错误消息中重复整行输入,添加任何您喜欢的解析尝试信息。

如果
scanf
没有返回
2
,您需要清除缓冲区。然后,缓冲区中有一些东西不能解释为
int
,例如字母。空格(以及开头的新行)将被忽略。请注意,这不是换行字符的问题,而是无效字符留在
stdin
scanf
中的问题,看到它们,失败,重复。。。仅供参考,
%d
跳过前导空格字符。