Search code examples
cinputprintfstderr

check input and stderr


I am trying to write program that will read integers from stdin and print their gcd. If both integers is prime, I print "prime". Before the end program print to stderr - "DONE". When user input wrong data I want to print to to stderr - "ERROR". So I write this code:

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

int main() {
    int in1, in2;
    int tmp;
    while (1) {
        tmp = scanf("%d %d", &in1, &in2);
        if (tmp == EOF) {
            fprintf(stderr, "DONE\n");
            break;
        }
        if (tmp != 2) {
            fprintf(stderr, "ERROR\n");
        } else if ((nd(in1) == 1) && (nd(in2) == 1)) printf("prime\n");
                    // nd(int a) return 1 when a is prime  
                else printf("%d\n", gcd(in1, in2));
    }
    return 0;
}

I want continue work after "ERROR". But it doesn't work, I tried add continue; after fprintf(stderr, "ERROR\n");, but it also doesn't work. So, I want to:

- program run
5 10
5
1 3 
prime
1 0.9
error
// not break here!
10 2 
2
...
//EOF
DONE
- program stop

All is work, except "ERROR", I have this:

- program run
5 0.9
ERROR
ERROR
ERROR
ERROR
...
//never stop

I understand that in loop cycle it's correct work. My question is what I have to change to switch from 'what I have' to 'what I want'.


Solution

  • scanf() has problems trying to cope with unexpected input. Instead, read a line with fgets()

    char buf[100];
    if (fgets(buf, sizeof buf, stdin) == NULL) {
      fprintf(stderr, "DONE\n");
      break;
    }
    if (sscanf(buf, "%d%d", &in1, &in2) != 2) {
      fprintf(stderr, "ERROR\n");
    } else if ((nd(in1) == 1) && (nd(in2) == 1)) {
      printf("prime\n");
    } else {
      printf("%d\n", gcd(in1, in2));
    }
    

    Amended code to look for extra text on the line.

    // if (sscanf(buf, "%d%d", &in1, &in2) != 2) {
    //   fprintf(stderr, "ERROR\n");
    int n = 0;
    if (sscanf(buf, "%d%d %n", &in1, &in2, &n) != 2 || buf[n]) {
      fprintf(stderr, "ERROR\n");
    } ...