Printf () prints a line without a new line in stdout in line buffer mode after scanf ()

I know that most terminals work by default in line buffering mode. that is, the output is buffered and not directed to stdout until a newline character is encountered.

So I expected this to not print anything (at least until the buffer is full):

int main() { while(1) { printf("Haha"); sleep(1); } return 0; } 

It really doesn't print anything for a short period of time.

If I want to print "Haha" every second, I can either printf("Haha\n") or do fflush(stdout) after printf. (I know this is not so portable, but this solution nonetheless)

Now I recall the very classic scanf program (with my addition to while (1) loop, to prevent buffer flushing when the program exits):

 int main() { char char_in; while(1) { printf("Haha. Input sth here: "); scanf("%c", &char_in); } return 0; } 

Now the program prints Haha. Input sth here: Haha. Input sth here: (and wait for input). It is not here if I delete the scanf statement. Why is this so?

Thanks.

+8
c stdio
source share
1 answer

Now the program prints Haha. Input sth here: Haha. Input sth here: (and wait for input). It is not here if I delete the scanf statement. Why is this so?

Since the standard ( N1570 .. "almost C11") says so, Β§5.1.2.3 / 6 (emphasis mine):

Least requirements for the corresponding implementation:

[..]

  • The dynamics of the input and output of interactive devices should take place, as indicated in 7.21.3. The purpose of these requirements is that unbuffered or linearly buffered output appears as soon as possible to ensure that request messages are displayed before a program is awaiting input .

[..]

Despite the fact that your output does not contain a new line and is sent to a line with stdout buffering, it should appear before your program can wait for input. This is due to the fact that stdout and stdin connected to the terminal and therefore (Note: this is a specific implementation!) That the standard calls "interactive devices".

+3
source share

All Articles