在 Eclipse 中将 fgets(char* c, int i, file* f) 与 printf() 结合使用 - CDT。输出顺序不正确。!

Using fgets(char* c, int i, file* f) with printf() for C in Eclipse - CDT. The order of output is not correct.!

#include <stdio.h>
enum { max_string = 127 };
static char ch[max_string+1] = "";

int main(int argc, char ** argv){
    printf("Type a String: \n");
    fgets(ch, max_string, stdin);
    printf("the string is: %s", ch);
    return 0;
}

我用过这段代码,控制台的输出是

hello world
Type a String: 
the string is: hello world

'hello world' 是我给出的输入。

我的问题是为什么在这种情况下没有维护订单。因为 printf() 应该在 fgets() 之前工作,但这里不是这样。我已经在 Code::Blocks 中使用相同的编译器进行了检查。它在那里按顺序工作。 但是在 Eclipse-MARS CDT 的情况下,我发现它是错误的。

我假设您在 Windows 上 运行ning,并且 运行 在 CDT 上 [=] 上使用 Eclipse CDT 中的控制台输出 longstanding problem 35=].

错误被标记为 "WONTFIX",评论解释了为什么这个问题很难修复。他们确实提出了几种解决方法:

  • 每次调用 printf 后调用 fflush(stdout)。这会在每次输出操作后显式刷新输出缓冲区。
  • 在程序开头调用 setvbuf(stdout, NULL, _IONBF, 0) 一次。这将完全禁用输出缓冲。
  • 按照 here 所述使用 CDT 的实验性 "winpty" 支持。这试图使 Eclipse 的控制台具有与真实终端相同的行为,包括行缓冲。

我有一个更简单的解决方案建议:使用 Eclipse 构建你的程序,但是 运行 它直接来自终端(命令提示符)。然后您将获得正确的终端行为而无需任何解决方法。