scanf函数忽略,无限循环 [英] scanf ignoring, infinite loop

查看:292
本文介绍了scanf函数忽略,无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int flag = 0;
int price = 0;
while (flag==0)
{
    printf("\nEnter Product price: ");
    scanf("%d",&price);
    if (price==0) 
        printf("input not valid\n"); 
    else 
        flag=1;
}

当我输入一个有效的数字,循环结束预期。但是,如果我输入的东西是不是一个数字,如你好,那么code进入一个无限循环。它只是不断印刷输入产品价格:输入无效。不过,这并不等我进入一个新的号码。这是为什么?

When I enter a valid number, the loop ends as expected. But if I enter something that isn't a number, like hello, then the code goes into an infinite loop. It just keeps printing Enter Product price: and input not valid. But it doesn't wait for me to enter a new number. Why is that?

推荐答案

当你输入的东西是不是一个数字, scanf函数将失败,将离开这些字符输入。所以,如果你输入你好,scanf函数会看到 ^ h ,拒绝它作为无效十进制数,并留下它的输入。通过循环下一次, scanf函数将再次看到 H,所以它只是不断无休止的循环下去。

When you enter something that isn't a number, scanf will fail and will leave those characters on the input. So if you enter hello, scanf will see the h, reject it as not valid for a decimal number, and leave it on the input. The next time through the loop, scanf will see the h again, so it just keeps looping forever.

一个解决这个问题是要读取输入的整条生产线与与fgets ,然后解析与的sscanf 。这样一来,如果的sscanf 失败,没有什么是留在输入。用户将需要输入与fgets 阅读新行。

One solution to this problem is to read an entire line of input with fgets and then parse the line with sscanf. That way, if the sscanf fails, nothing is left on the input. The user will have to enter a new line for fgets to read.

沿着这些路线的内容:

char buffer[STRING_SIZE];
...
while(...) {
    ...
    fgets(buffer, STRING_SIZE, stdin);
    if ( sscanf(buffer, "%d", &price) == 1 )
        break;   // sscanf succeeded, end the loop
    ...
}

如果你只是做一个的getchar 作为另一个答案的建议,那么你可能会错过 \\ n 字符这时,数字之后用户键入的东西(例如,一个空格,后面可能跟着其它字符)。

If you just do a getchar as suggested in another answer, then you might miss the \n character in case the user types something after the number (e.g. a whitespace, possibly followed by other characters).

您应该始终测试的sscanf 的返回值。它返回分配的转换次数,所以,如果返回值是不相同的要求的转换次数,这意味着该解析失败。在这个例子中,有要求,所以的sscanf 1转换返回1时,它的成功。

You should always test the return value of sscanf. It returns the number of conversions assigned, so if the return value isn't the same as the number of conversions requested, it means that the parsing has failed. In this example, there is 1 conversion requested, so sscanf returns 1 when it's successful.

这篇关于scanf函数忽略,无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆