[scanf如果输入了错误的格式,则会卡在循环中

问题描述 投票:0回答:1

所以我遇到了这个问题,并一直试图弄清为什么会这样。考虑一个像这样的简单程序:

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变量中是否有缓冲区溢出?但是它每次都被初始化为零吗?我可以使用该功能的另一个更安全的版本吗?

c scanf
1个回答
0
投票

我相信会发生什么情况,它将读取10部分,并且.08将保留在输入缓冲区中,因此在下一次迭代中,它将尝试将其解析为十进制值,并且将失败。由于失败,因此.08保留在输入缓冲区中,因此它将在下一次迭代中再次尝试并再次失败,并且此操作将继续下去。

© www.soinside.com 2019 - 2024. All rights reserved.