简体   繁体   中英

c - while loop keeps ignoring scanf after bad input

I've searched the forum for the solution, but still in confusion about the output my code produces.

So, the program is pretty simple.

It gets two numbers at the input until reaches the end of file.
If the input is bad, it should print error to stdout and proceed to the next pair.
If both are primes, it prints out prime . Otherwise, it prints their GCD.

Problem is, that if the input is bad, ie either one or both numbers are not actually numbers, the program skips scanf and keeps on printing error to stderr.
Yet, during debugging, I found out that all the next iterations scanf() goes through, it returns 0 as if nothing was inputted at all.
And the prompt is inactive for inputting, since the program constantly prints to stderr.

nd and nsd are functions returning greatest divider and greatest common divisor respectively.

The main program is following:

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

I put together a simple program to validate the return value:

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

Here's that results of that program: INP INP

That's because the letters are actually being stored.

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

值

The values are being stored incorrectly, but the program is still making do. By storing the results with scanf, they aren't actually causing an error.

The most robust way of validating the inputs would be to make sure that you have both, like with this solution . Basically,

if (inp_status != 2){
    break;
}

instead of

if (inp_status == EOF){
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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