简体   繁体   中英

Printf not working with scanf

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?

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.

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

将换行符“ \\ n”添加到您的printf行中,如下所示:

printf("Write a number: \n");

您可能希望在每个这些printf语句中使用\\ n。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM