Reputation: 173
Hi i am new to the programing and for example in my code:
#include <stdio.h>
int main (void){
int a;
printf("Write a number: ");
scanf("%d", &a);
printf("Your written number was: %d", a);
return 0;
}
Printf
does not write "write a number" in console when i start the program but only after i already inserted the number and pressed enter.
I have already done some research and found out for this code:
setvbuf(stdout, NULL, _IONBF, 0);
when i paste this into my program it works as it should but i am wondering why do i have to do that?
Upvotes: 1
Views: 238
Reputation: 6995
Add linefeed "\n" to your printf lines like so:
printf("Write a number: \n");
Upvotes: 0
Reputation: 121427
when i paste this into my program it works as it should but i am wondering why do i have to do that?
It's because printf()
is usually line-buffered when attached to a terminal. So disabling the buffering with the call to setvbuf()
makes stdio library to not buffer at all.
You can also use fflush(stdout);
after the printf()
call to flush out the buffered output. The same can be done with setbuf(stdout, NULL);
as well.
You can also add a \n
at the end of printf()
statement to force the flushing. But this will work only if the output goes to a terminal device.
For example, if you do (on a unix-like system):
./a.out > output_file
then the \n
will not flush the buffer.
Out of the two options (setbuf()
and fflush()
),fflush(stdout);
is probably the better option in most cases. Since disabling the buffering completely can have negative impact on performance (which is the primary reason for buffering in the first place) whereas fflush()
can be judiciously used at the right place when you think it's necessary.
Upvotes: 1
Reputation: 60037
printf
has a buffer. It is a mechanism to make code run faster by not having to switch between the user context and the kernel context. To get over this you can tell the code to flush the buffer - i.e. send it to the operating system. This can be done by
fflush(stdout);
After a printf
. If the printf
contains a new line this is done automatically.
Upvotes: 1