为什么在循环中,带有 %d 的 scanf() 不等待用户输入,以防它之前收到无效输入? [英] Why inside a loop, scanf() with %d does not wait for the user input in case it received an invalid input previously?

查看:60
本文介绍了为什么在循环中,带有 %d 的 scanf() 不等待用户输入,以防它之前收到无效输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 scanf() 在得到预期结果或没有得到预期结果时返回的结果.发生的情况是它卡在while()`循环中.

I am using what scanf() returns when it gets what is expects or when it doesn't. What happens is it gets stuck in thewhile()` loop.

据我所知 test = scanf("%d", &testNum); 如果它收到一个数字,则返回 1,否则返回 0.

To my knowledge test = scanf("%d", &testNum); returns a 1 if it receives a number and a 0 if not.

我的代码:

#include<stdio.h>

int main(void) {
    while (1) {
        int testNum = 0;
        int test;
        printf("enter input");
        test = scanf("%d", &testNum);
        printf("%d", test);
        if (test == 0) {
            printf("please enter a number");
            testNum = 0;
        }
        else {
            printf("%d", testNum);
        }
    }
    return(0);
}

推荐答案

这里的问题是,在遇到无效输入时,(例如一个字符),错误的输入不是消耗,它保留在输入缓冲区中.

The problem here is, upon encountring an invalid input, (a character, for example), the incorrect input is not consumed, it remains in the input buffer.

因此,在下一个循环中,scanf() 再次读取相同的无效输入.

So, in the next loop, the same invalid input is again read by scanf().

您需要在识别出错误输入后清理缓冲区.一个非常简单的方法是,

You need to clean up the buffer after identifying incorrect input. A very simple approach will be,

    if (test == 0) {
        printf("please enter a number");
        while (getchar() != '\n');  // clear the input buffer off invalid input
        testNum = 0;
    }

也就是说,要么初始化 test,要么删除 printf("%d", test);,因为 test 是一个自动变量,除非明确初始化,否则包含不确定值.尝试使用可以调用 未定义行为.

That said, either initialize test, or remove printf("%d", test);, as test being an automatic variable, unless initialized explicitly, contains indeterminate value. Attempt to use that can invoke undefined behavior.

也就是说,为了挑剔return 不是一个函数,不要让它看起来像一个函数.这是一个 staement,所以 return 0; 对眼睛来说更舒缓,而且更容易混淆.

That said, just to be nit-picky, return is not a function, don't make it look like one. It's a staement, so return 0; is much more soothing to the eyes and much less confusing, anyway.

这篇关于为什么在循环中,带有 %d 的 scanf() 不等待用户输入,以防它之前收到无效输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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