scanf()的行为不端 [英] scanf() misbehaving

查看:146
本文介绍了scanf()的行为不端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很短的片段,在一个整数读取:

I have a very short snippet that reads in an integer:

#include <stdio.h>

int main() {
    while (1) {
        int i = 0;
        int r = scanf("%d", &i);

        if (r == EOF) {
            printf("Error using scanf()\n");
        } else if (r == 0) {
            printf("No number found\n");
        } else {
            printf("The number you typed in was %d\n", i);
        }
    }
}

但问题是,如果我输入任何字母,它只是不断通过循环和打印出来,而不是等待下一个输入'未发现号。

but the problem is that if I input any letter, it just keeps looping through and prints out 'No number found' instead of waiting for the next input.

我在做什么错了?

推荐答案

在使用 scanf函数,如果你尝试做一个读操作,发现不匹配的数据预期的格式, scanf函数叶未知数据背后由未来拿起读操作。在这种情况下,发生的事情是,你想读取用户格式的数据,用户的数据不匹配预期的格式,因此它无法读取任何东西。然后,它绕一圈再次尝试阅读和查找相同的违规输入它之前,必须然后循环再等。

When using scanf, if you try doing a read operation and the data found doesn't match the expected format, scanf leaves the unknown data behind to be picked up by a future read operation. In this case, what's happening is that you're trying to read formatted data from the user, the user's data doesn't match your expected format, and so it fails to read anything. It then loops around to try to read again and finds the same offending input it had before, then loops again, etc.

要解决这个问题,你只需要消耗的粘住了输入的字符。这样做的一个方法是调用龟etc 来读取字符,直到检测到新行,这将刷新任何违规的字符:

To fix this, you just need to consume the characters that gummed up the input. One way to do this would be to call fgetc to read characters until a newline is detected, which will flush any offending characters:

while (1) {
    int i = 0;
    int r = scanf("%d", &i);

    if (r == EOF) {
        printf("Error using scanf()\n");
    } else if (r == 0) {
        printf("No number found\n");

        /* Consume bad input. */
        while (fgetc(stdin) != '\n')
            ;

    } else {
        printf("The number you typed in was %d\n", i);
    }
}

希望这有助于!

这篇关于scanf()的行为不端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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