What does flushing the buffer mean?

前端 未结 3 494
别那么骄傲
别那么骄傲 2020-11-27 10:28

I am learning C++ and I found something that I can\'t understand:

Output buffers can be explicitly flushed to force the buffer to be written. By def

3条回答
  •  独厮守ぢ
    2020-11-27 10:39

    You've quoted the answer:

    Output buffers can be explicitly flushed to force the buffer to be written.

    That is, you may need to "flush" the output to cause it to be written to the underlying stream (which may be a file, or in the examples listed, a terminal).

    Generally, stdout/cout is line-buffered: the output doesn't get sent to the OS until you write a newline or explicitly flush the buffer. The advantage is that something like std::cout << "Mouse moved (" << p.x << ", " << p.y << ")" << endl causes only one write to the underlying "file" instead of six, which is much better for performance. The disadvantage is that a code like:

    for (int i = 0; i < 5; i++) {
        std::cout << ".";
        sleep(1); // or something similar
    }
    
    std::cout << "\n";
    

    will output ..... at once (for exact sleep implementation, see this question). In such cases, you will want an additional << std::flush to ensure that the output gets displayed.

    Reading cin flushes cout so you don't need an explicit flush to do this:

    std::string colour;
    std::cout << "Enter your favourite colour: ";
    std::cin >> colour;
    

提交回复
热议问题