C 检查输入和stderr

C 检查输入和stderr,c,input,printf,stderr,C,Input,Printf,Stderr,我试图写一个程序,从标准输入中读取整数并打印它们的gcd。如果两个整数都是素数,我打印“素数”。在结束程序之前,打印到stderr-“完成”。当用户输入错误数据时,我想打印到stderr-“错误”。所以我写了这段代码: #include "stdio.h" #include "nd.h" #include "nsd.h" int main() { int in1, in2; int tmp; while (1) { tmp = scanf("%d %d"

我试图写一个程序,从标准输入中读取整数并打印它们的gcd。如果两个整数都是素数,我打印
“素数”
。在结束程序之前,打印到
stderr
-
“完成”
。当用户输入错误数据时,我想打印到
stderr
-
“错误”
。所以我写了这段代码:

#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;
}
我想在
出现“错误”
后继续工作。但它不起作用,我尝试添加
继续
fprintf之后(stderr,“ERROR\n”),但它也不起作用。因此,我想:

- program run
5 10
5
1 3 
prime
1 0.9
error
// not break here!
10 2 
2
...
//EOF
DONE
- program stop
一切正常,除了“错误”
,我有:

- program run
5 0.9
ERROR
ERROR
ERROR
ERROR
...
//never stop
我知道在循环周期中它是正确的工作。我的问题是我必须改变什么才能从“我拥有的”切换到“我想要的”。

scanf()
在处理意外输入时遇到问题。相反,阅读带有
fgets()的行


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

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

非常有帮助,谢谢。只有一个补充问题。输入:
0,2;0; //必须按/n键,否则出错;错误但必须为:
0,2;错误
所以如果我输入
\n
错误
,但是如果我输入
2 0.2
,那么
0
(0.2不是整数,所以必须是
错误
)@Alexey Sharov
stdin
通常是行缓冲的,所以在输入
'\n'
之前,代码看不到任何东西。因此需要
'\n'
。你的第二个评论-->修正了答案。
// 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");
} ...