printf not printing on console

Mr T. picture Mr T. · Oct 23, 2012 · Viewed 183.8k times · Source

I’m getting started in the C language. I am using eclipse (juno) as my IDE and installed CDT plugin. I have also unpacked mingw64 (GCC Compiler). I wrote a very simple program to see if it works. This is my code:

#include <stdio.h>

int main()
{
    int age;
    printf("Hello, please enter your age:\n");
    scanf("%d", &age);
    printf("Your age is %d", age);
    return 0;
}

The problem is that the output buffer is filled with the string value of the first printf but does not output it to the console. I have to enter a number, and only then the buffer pours all the data to the console so I see the console something like this:

1
Hello, please enter your age:
Your age is 1

instead of what is expected that is:

Hello, please enter your age:
1
Your age is 1

Now, I found that I can use fflush(stdout) after the first printf but I don't think that this solution is elegant and even necessary. Any ideas on how I can overcome this?

EDIT - because I'm learning this in my university, I can't use anything that wasn't learned in the course so I can only use printf and scanf

NEW EDIT - I think I have found an explanation for this. As I said, I am outputting to the console view inside Eclipse. The strange thing is that if I compile and run the program from the command line of Windows, I get the wanted result. Therefore, I think that eclipse is actually writing the output to a file and presenting it in the console window. How can I force eclipse to open a real command line window in my run configurations?

Answer

kliteyn picture kliteyn · Oct 23, 2012

Output is buffered.

stdout is line-buffered by default, which means that '\n' is supposed to flush the buffer. Why is it not happening in your case? Dunno. Need more info about your application/environment.

However, you can control buffering with setvbuf():

setvbuf(stdout, NULL, _IOLBF, 0);

This will force stdout to be line-buffered.

setvbuf(stdout, NULL, _IONBF, 0);

This will force stdout to be unbuffered, so you won't need to use fflush(). Note that it will severely affect application performance if you have lots of prints.