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

送分小仙女□ 提交于 2019-11-27 08:19:20

问题


#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' is the input which I give.

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.


回答1:


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

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

  • 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.

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.



来源:https://stackoverflow.com/questions/34604947/using-fgetschar-c-int-i-file-f-with-printf-for-c-in-eclipse-cdt-the-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!