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