繁体   English   中英

c - while循环在输入错误后继续忽略scanf

[英]c - while loop keeps ignoring scanf after bad input

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

所以,该程序非常简单。

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

问题是,如果输入不好,即一个或两个数字实际上都不是数字,程序会跳过scanf并继续向stderr打印错误。
然而,在调试期间,我发现scanf()所有下一次迭代都经过,它返回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;
}

我整理了一个简单的程序来验证返回值:

#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;
}

这是该计划的结果: INP INP

那是因为这些字母实际上是存储的。

#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存储结果,它们实际上不会导致错误。

验证输入的最有效方法是确保您同时拥有这两种方法,就像使用此解决方案一样 基本上,

if (inp_status != 2){
    break;
}

代替

if (inp_status == EOF){
    break;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM