Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

c - printf() prints string without newline to stdout in line buffer mode after scanf()

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

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

The least requirements on a conforming implementation are:

[..]

  • The input and output dynamics of interactive devices shall take place as specified in 7.21.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input.

[..]

Even though your output does not contain a newline and is send to a line buffered stdout, it has to appear before your program is allowed to wait for input. This is because stdout and stdin are connected to a terminal and thus are (Attention: This is implementation defined!) what the standard calls "interactive devices".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...