所以我遇到了这个问题,并一直试图弄清为什么会这样。考虑一个像这样的简单程序:
while ( 1 ) {
printf("\nPlease enter your selection: ");
int choice = 0;
scanf("%d", &choice);
}
现在假设我们可以输入整数形式的任何数字,程序将按预期运行,并继续要求输入更多内容:
Please enter your selection: 9
Please enter your selection: 2
Please enter your selection: 1
...
但是如果我输入一个浮点数而不是整数,那么它将永远陷入无限循环中:
Please enter your selection: 10.08
Please enter your selection:
Please enter your selection:
Please enter your selection:
Please enter your selection:
Please enter your selection:
Please enter your selection:
Please enter your selection:
Please enter your selection:
Please enter your selection:
Please enter your selection:
...
怎么来?我知道我输入了错误的格式,但是我假设它只会读取数字的整数格式,而丢弃其余的格式,但是我现在发现情况并非如此。为什么会这样?输入choice
变量中是否有缓冲区溢出?但是它每次都被初始化为零吗?我可以使用该功能的另一个更安全的版本吗?
我相信会发生什么情况,它将读取10
部分,并且.08
将保留在输入缓冲区中,因此在下一次迭代中,它将尝试将其解析为十进制值,并且将失败。由于失败,因此.08
保留在输入缓冲区中,因此它将在下一次迭代中再次尝试并再次失败,并且此操作将继续下去。