为什么通过scanf()输入一个非预期的值类型会导致这个程序进入死循环
Why does inputting an unexpected value type via scanf() cause this program to enter an infinite loop
考虑以下代码片段:
int n;
int a[100];
int main()
{
printf("\nThis program will sort a given list of between 1 and 100 integers.\n\n");
int ready = 0;
while(!ready)
{
printf("How many integers are in your list? ");
scanf("%d",&n);
if(n>100)
{
printf("\n\nError:\tToo many integers.\n\tThis program can only handle up to 100 integers.\n\n\n");
}
else if (n<1)
{
printf("\n\nError:\tNot enough integers.\n\tThis program requires at least 1 integer to sort.\n\n\n");
}
else ready=1;
}
}
如果你在提示符下输入任何整数,它会正常工作,但如果你输入一个字符,它就会开始不断输出:
How many integers are in your list?
Error: Too many integers.
This program can only handle up to 100 integers.
...
...
recurse over and over
显然它与 scanf() 函数有关,但我想知道导致这种抽象泄漏的原因。
我已经习惯了有漂浮物和救生衣的语言,我正在努力适应和C一起在游泳池深处游泳。
如果您输入一个字符,则 scanf()
会失败,之后不会定义结果,而且输入不会被消耗并保留在缓冲区中递归地获取相同的值,从而导致您的 scanf() 重复失败.
所以你应该这样做
if(scanf("%d",&n) == 1)
// Do your stuff
因为 scanf
函数只会提取正确的输入。如果输入不正确,循环迭代时输入仍将在输入缓冲区中,下一次调用 scanf
将读取完全相同的输入。
您可能想要使用 scanf
to determine if you should exit the loop, or use e.g. fgets
to read and extract the complete line, and then use e.g. strtol
(或 sscanf
)的 return 值来获取值。
考虑以下代码片段:
int n;
int a[100];
int main()
{
printf("\nThis program will sort a given list of between 1 and 100 integers.\n\n");
int ready = 0;
while(!ready)
{
printf("How many integers are in your list? ");
scanf("%d",&n);
if(n>100)
{
printf("\n\nError:\tToo many integers.\n\tThis program can only handle up to 100 integers.\n\n\n");
}
else if (n<1)
{
printf("\n\nError:\tNot enough integers.\n\tThis program requires at least 1 integer to sort.\n\n\n");
}
else ready=1;
}
}
如果你在提示符下输入任何整数,它会正常工作,但如果你输入一个字符,它就会开始不断输出:
How many integers are in your list?
Error: Too many integers.
This program can only handle up to 100 integers.
...
...
recurse over and over
显然它与 scanf() 函数有关,但我想知道导致这种抽象泄漏的原因。
我已经习惯了有漂浮物和救生衣的语言,我正在努力适应和C一起在游泳池深处游泳。
如果您输入一个字符,则 scanf()
会失败,之后不会定义结果,而且输入不会被消耗并保留在缓冲区中递归地获取相同的值,从而导致您的 scanf() 重复失败.
所以你应该这样做
if(scanf("%d",&n) == 1)
// Do your stuff
因为 scanf
函数只会提取正确的输入。如果输入不正确,循环迭代时输入仍将在输入缓冲区中,下一次调用 scanf
将读取完全相同的输入。
您可能想要使用 scanf
to determine if you should exit the loop, or use e.g. fgets
to read and extract the complete line, and then use e.g. strtol
(或 sscanf
)的 return 值来获取值。