检查输入和标准错误

check input and stderr

我正在尝试编写将从标准输入读取整数并打印其 gcd 的程序。如果两个整数都是素数,我打印 "prime"。在结束程序之前打印到 stderr - "DONE"。当用户输入错误的数据时,我想打印到 stderr - "ERROR"。所以我写了这段代码:

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

我想在 "ERROR" 之后继续工作。但是不行,我试过在fprintf(stderr, "ERROR\n");之后加continue;,还是不行。所以,我想:

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

一切正常,除了"ERROR",我有这个:

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

我知道在循环中它是正确的。我的问题是我必须更改什么才能从 'what I have' 切换到 'what I want'。

scanf() 在尝试处理意外输入时遇到问题。相反,阅读 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));
}

修改代码以查找行中的额外文本。

// 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");
} ...