c - while 循环在输入错误后一直忽略 scanf

c - while loop keeps ignoring scanf after bad input

我已经在论坛中搜索了解决方案,但仍然对我的代码生成的输出感到困惑。

所以,这个程序非常简单。

它在输入中得到两个数字,直到到达文件末尾。
如果输入错误,它应该将错误打印到标准输出并继续处理下一对。
如果两者都是质数,它会打印出 prime。否则,它会打印他们的 GCD。

问题是,如果输入错误,即一个或两个数字实际上不是数字,程序会跳过 scanf 并继续将错误打印到 stderr。
然而,在调试过程中,我发现接下来的所有迭代 scanf() 都通过了,returns 0 就好像什么都没输入一样。
并且提示对于输入是无效的,因为程序不断地打印到 stderr。

ndnsd 分别是返回最大除数和最大公约数的函数。

主要程序如下:

#include <stdio.h>
#include "nd.h"
#include "nsd.h"

int main() 
{
int a;
int b;
int inp_status = 0;
while (1){
        inp_status=scanf(" %d %d", &a, &b);
        if (inp_status == EOF){
            break;
        } else if (inp_status < 2){
            fprintf(stderr, "Error: bad input\n");
        } else {
            if (a == 1 || b == 1){
                printf("1\n");
            } else if (nd(a) == 1 && nd(b) == 1){
                printf("prime\n");
            } else {
                printf("%d\n",nsd(a,b));
            }
        }
}
fprintf(stderr, "DONE\n");
return 0;
}

我编写了一个简单程序来验证 return 值:

#include <stdio.h>

int main()
{
    int a;
    int b;
    int inp_status = 0;

    inp_status = scanf(" %d %d", &a, &b);
    printf("INP status: %d\n", inp_status);
    printf("EOF = %d\n", EOF);

    return 0;
}

这是该程序的结果:

那是因为实际上是在存储字母。

#include <stdio.h>

int main()
{
    int a;
    int b;
    int inp_status = 0;

    inp_status = scanf(" %d %d", &a, &b);
    printf("INP status: %d\n", inp_status);
    printf("EOF = %d\n", EOF);
    printf("Values stored: a = %d, b = %d\n", a, b);

    return 0;
}

值存储不正确,但程序仍在执行。通过使用 scanf 存储结果,它们实际上并没有导致错误。

验证输入的最可靠方法是确保您同时拥有这两种输入,就像 this solution 一样。基本上,

if (inp_status != 2){
    break;
}

而不是

if (inp_status == EOF){
    break;
}