【问题标题】:An EOF bug in CLionCLion 中的 EOF 错误
【发布时间】:2018-04-27 19:22:14
【问题描述】:
#include <stdio.h>

/*Checking whether the value of (getchar() != EOF) is 1,
  when not reaching the EOF*/
main() {
    int c;

    printf("Please enter character:\n");
    while (c = getchar() != EOF) {
        printf("%d\t", c);
    }
    printf("%d - at EOF\n", c);
} 

我在CLion中运行过这段代码,但是出现了一个问题,第一个printf()中的内容直到我输入了一些字才出现。

有一个例子。

error
^D
Please enter character:
1   1   1   1   1   1   0 - at EOF

我知道它可能是因为我已禁用了run.processes.with.pty在注册表中,因为句子“请输入字符:”选项可用时位于正确的位置。但是如果我不这样做,我就不能使用 Ctrl+D 来发送 EOF。另外,似乎只有当我在字符后的新空行中键入 Ctrl+D 时结果才正确。

平台:Windows 10,工具链:MinGW

顺便说一句,我也试过 Cygwin。同样的问题再次发生。有什么想法吗?

【问题讨论】:

  • 因为operator precedence你有:while (c = (getchar() != EOF)) {
  • main() 应该是int main(void)

标签: c clion


【解决方案1】:

问题是

c = getchar() != EOF

真的只是

c = (getchar() != EOF)

你想要的是

(c = getchar()) != EOF

如果您使用c = getchar() != EOF,许多编译器会生成警告

$ cc -c test.c -Wall -Wextra
test.c:5:1:警告:返回类型默认为“int”[-Wimplicit-int]
 主要的() {
 ^~~~
test.c:在函数“main”中:
test.c:9:12:警告:建议在赋值周围使用括号作为真值 [-W括号]
     而(c = getchar()!= EOF){
            ^

这就是建议启用警告的原因。对于新项目,我认为-Wall -Wextra 是最低要求。

【讨论】:

    【解决方案2】:

    运算符优先级。 @Johnny Mopp

    c = getchar() != EOFc = (getchar() != EOF) 相同,当然不是 OP 想要的。

    // while (c = getchar() != EOF)
    while ((c = getchar()) != EOF)
    

    但是出现了一个问题,就是第一个printf()里面的内容一直没有出现,直到我输入了一些字。

    stdout 通常被缓冲。它可能是line 缓冲或完全缓冲 或根本没有。使用fflush(stdout) 确保发布输出。

    printf("Please enter character:\n");
    fflush(stdout); //add
    while (c = getchar() != EOF) {
      printf("%d\t", c);
      fflush(stdout); //add
    }
    printf("%d - at EOF\n", c);
    

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 2011-11-26
      • 2022-06-11
      • 2014-10-17
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      相关资源
      最近更新 更多