I am aware that most terminals are by default in line buffer mode. i.e. output is buffered and not directed to stdout until a new-line character is encountered.
So I would expect this to print nothing (at least before the buffer is filled up):
int main() {
while(1) {
printf("Haha");
sleep(1);
}
return 0;
}
It indeed prints nothing for a short period of time.
If I want to print "Haha" every second, I can either printf("Haha
")
or do fflush(stdout)
after printf. (I know this is not so portable, but it's a solution nonetheless)
Now I recall the very classic scanf program (with my addition to while(1) loop to prevent buffer flushing on program exit):
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:
(and wait for my input). It is not here if I remove the scanf statement. Why is that so?
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…