【问题标题】:check input and stderr检查输入和标准错误
【发布时间】:2015-11-01 22:01:53
【问题描述】:

我正在尝试编写从标准输入读取整数并打印它们的 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

我知道在循环循环中它是正确的工作。我的问题是我必须改变什么才能从“我拥有的”转变为“我想要的”。

【问题讨论】:

    标签: c input printf stderr


    【解决方案1】:

    scanf() 在处理意外输入时遇到问题。相反,请使用fgets()

    阅读 line
    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");
    } ...
    

    【讨论】:

    • 非常有帮助,谢谢。只有一个额外的问题。输入:0 0,2; 0; //must press /n than error; ERROR; 但必须是:0 0,2; ERROR;
    • 所以如果我输入\n而不是ERROR,但是如果我输入2 0.2然后0(0.2不是整数所以必须是ERROR
    • @Alexey Sharov stdin 通常是 line 缓冲的,因此在输入 '\n' 之前,您的代码看不到任何内容。所以需要'\n'。您的第二条评论 --> 修改后的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2013-05-11
    • 1970-01-01
    相关资源
    最近更新 更多