【问题标题】:C : File redirection is not workingC:文件重定向不起作用
【发布时间】:2015-12-16 23:26:04
【问题描述】:

我正在尝试在下面的C程序中做一个简单的scanfprintf

  1. 获取用户输入
  2. 检查用户输入是否正确,如果正确,打印出来,否则显示错误消息

代码如下:

#include <stdio.h>

int main() {  
    int latitude;
    int scanfout;
    int started = 1;

    puts("enter the value:");

    while (started == 1) {
        scanfout = scanf("%d", &latitude);
        if (scanfout == 1) {
            printf("%d\n", latitude);
            printf("ok return code:%d\n", scanfout);
            puts("\n");
        } else {
            puts("value not a valid one");
            printf("not ok return code:%d\n", scanfout);        
        }
        fflush(stdin);
    }
    return 0;
}

尝试在命令终端上编译和运行它,程序可以工作。 命令行输出:

enter the value:
1
1
ok returncode:1

0
0
ok returncode:1

122.22
122
ok returncode:1

sad
value not a valid one
not ok returncode:0

如您所见,该程序只是扫描用户输入并将其打印出来,它在命令行中运行良好,但是当它尝试将输入重定向到文本文件时说:

test < in.txt

程序不起作用,else 部分中的打印语句在无限循环中继续打印。文本文件in.txt 包含单个值12,而不是打印12,程序只是进入一个无限循环并打印:

value not a valid one
not ok returncode:0
value not a valid one
not ok returncode:0
value not a valid one
not ok returncode:0
value not a valid one
not ok returncode:0

谁能帮我解决这个问题?代码是否正确,为什么它可以从命令行工作以及为什么文件重定向不起作用?帮助将不胜感激...

【问题讨论】:

  • 您的程序没有正确处理不正确的(非整数)输入。与重定向无关。 scanf 不消耗不匹配的输入。而fflush(stdin) 也不这样做(它在某些平台上是未定义行为,在 Linux 上它只刷新任何缓冲数据而不是未读数据)。
  • 尝试使用fgets,然后改用sscanfstrtol
  • kaylum,感谢您的回复,您是说程序没有正确处理不正确的数据,但是在运行 exe 时,如果我给出一个虚拟值:sadsdfs 或一些不正确的数据,它会打印else 部分中的代码,仅当我尝试将输入重定向到文件而不是用户输入时才会出现问题,如果您可以更正代码并向我显示错误的部分,这将非常有帮助..跨度>
  • in.txt 文件中究竟有什么内容?最好你应该显示该文件的十六进制转储。
  • 问题是fflush(stdin)。它通常是未定义的行为,充其量是不可预测的。它可能在特定系统上工作,但它并不总是工作(充其量是不可移植的) - 它当然不能在我的 Linux 系统上工作,并且来自终端的无效输入将导致您看到的无限循环。底线 - 避免做fflush(stdin)。例如:Using fflush(stdin)

标签: c file printf scanf


【解决方案1】:

您不测试文件结尾:当扫描输入文件时,程序进入无限循环,因为scanf 返回-1,程序报错并重试。

顺便说一句,如果输入文件中有数据无法转换为int,程序将永远循环尝试重新解析相同的输入,但徒劳无功。

请注意,fflush(stdin); 未在 C 标准中指定,它可能会或可能不会按照您的预期执行,尤其是从文件中。

这是一个更正的版本:

#include <stdio.h>

int main() {  
    int latitude, scanfout, c;

    puts("enter the value:");

    for (;;) {
        scanfout = scanf("%d", &latitude);
        if (scanfout == 1) {
            printf("%d\n", latitude);
            printf("ok return code:%d\n", scanfout);
            puts("\n");
        } else
        if (scanfout < 0) {
            break;   // End of file 
        } else {
            puts("value not a valid one");
            printf("not ok return code:%d\n", scanfout);        
        }
        /* read and ignore the rest of the line */
        while ((c = getchar()) != EOF && c != '\n')
            continue;
    }
    return 0;
}

【讨论】:

  • 嗨,你能更正代码并告诉我正确的代码吗,这会很有帮助....
猜你喜欢
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多