在Eclipse-CDT中将fgets(char * c,int i,file * f)与printf()一起用于C。输出顺序不正确! [英] Using fgets(char* c, int i, file* f) with printf() for C in Eclipse - CDT. The order of output is not correct.!

查看:82
本文介绍了在Eclipse-CDT中将fgets(char * c,int i,file * f)与printf()一起用于C。输出顺序不正确!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

我使用了这段代码,控制台中的输出为

I have used this code and the output in the console was

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

hello world是我提供的输入。

'hello world' is the input which I give.

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

My question is why isn't the order not maintained in this case. As printf() should work before fgets(), but here it isn't that way. I have checked with the same compiler in Code::Blocks. There it works in order. But in case of Eclipse-MARS CDT I find it erroneous.

推荐答案

我假设您正在Windows上运行,并且遇到了长期存在的问题与Windows上的Eclipse CDT中的控制台输出有关。

I assume you're running on Windows, and running into a longstanding problem with console output in Eclipse CDT on Windows.

该错误被标记为 WONTFIX,并且注释说明了为什么它是一个很难解决的问题。他们确实提出了几种解决方法:

The bug is marked as "WONTFIX", and the comments explain why it's a hard problem to fix. They do suggest several workarounds:


  • 在每次调用后调用 fflush(stdout) printf

  • 调用 setvbuf(stdout,NULL,_IONBF,0)会在每次输出操作后显式刷新输出缓冲区。您的程序。

  • 使用CDT的实验性 winpty支持,如此处。这试图使Eclipse的控制台具有与实际终端相同的行为,包括行缓冲。

  • Call fflush(stdout) after each call to printf. This flushes the output buffer explicitly after each output operation.
  • Call setvbuf(stdout, NULL, _IONBF, 0) once at the beginning of your program. This disables output buffering altogether.
  • Use CDT's experimental "winpty" support as described here. This attempts to make Eclipse's console have the same behaviour as a real terminal, including line buffering.

我有一个简单得多的解决方案可以建议:使用Eclipse 构建您的程序,但直接从终端(命令提示符)运行。然后,您将获得适当的终端行为,而无需任何变通办法。

I have a much simpler solution to suggest: build your program with Eclipse, but run it directly from a terminal (Command Prompt). Then you will get proper terminal behaviour without any workarounds.

这篇关于在Eclipse-CDT中将fgets(char * c,int i,file * f)与printf()一起用于C。输出顺序不正确!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆