Scanf 不等待输入就返回 0 [英] Scanf returns 0 without waiting for input

查看:43
本文介绍了Scanf 不等待输入就返回 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有用 C 编程过,今天我必须编写小代码.程序很简单——我想把两个整数相加.但是当我试图检查给定的输入是否是一个数字并且第一个 scanf 返回 0 时,第二个也返回 0 而不等待输入.代码:

I have never programmed in C and today I have to write small code. Program is very easy - I want to add two integers. But when I'm trying to check if given input is a number and first scanf returns 0, the second one returns 0 too without waiting for input. Code:

int main()
{
    int a = 0;
    int b = 0;
    printf("Number a:\n");
    if (scanf("%d", &a) != 1)
    {
        printf("Not a number. a=0!\n");
        a = 0;
    }
    printf("Number b:\n");
    if (scanf("%d", &b) != 1)
    {
        printf("Not a number. b=0!\n");
        b = 0;
    }
    printf("%d\n", a+b);
    return 0;
}

推荐答案

那是因为,一旦第一个 scanf() 失败,很可能是因为匹配失败,导致匹配失败,保留在输入缓冲区内,等待下一次调用使用.

That is because, once the first scanf() failed, it is probably because of matching failure, and the input which caused the matching failure, remains inside the input buffer, waiting to be consumed by next call.

因此,对 scanf() 的下一次调用也尝试立即使用驻留在输入缓冲区中的相同 invalid 输入,而不用等待显式的外部用户输入作为输入缓冲区不为空.

Thus, the next call to scanf() also try to consume the same invalid input residing in the input buffer immediately, without waiting for the explicit external user input as the input buffer is not empty.

解决方案:scanf() 的第一次输入失败后,您必须清理输入缓冲区,举个简单的例子,比如 while (getchar() != '\n'); 应该可以完成这项工作.

Solution: After the first input fails for scanf(), you have to clean up the input buffer, for a trivial example, something like while (getchar() != '\n'); should do the job.

这篇关于Scanf 不等待输入就返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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