Buffered and unbuffered stream

前端 未结 5 716
迷失自我
迷失自我 2020-12-10 00:07

In case of buffered stream it said in a book that it wait until the buffer is full to write back to the monitor. For example:

cout << \"hi\"; 
<         


        
5条回答
  •  盖世英雄少女心
    2020-12-10 00:33

    1. Each call to write to the terminal is slow, so to avoid doing slow things often the data is stored in memory until either a certain amount of data has been entered or the buffer is flushed manually with fflush or std::endl. The result of this is sometimes that text might not be written to the terminal at the moment you expect it to.

    2. Since the timing of error messages is more critical than normal output, the performance hit is ignored and the data is not buffered. However, since a string is passed in a single piece of data, it is written in one call (inside a loop somewhere).

    3. It world would still be in the buffer, but it's quite easy to prove this yourself by trying it in a 3 line program. However, your example will fail since you are attempting to write into unallocated memory. You should be taking input into a std::string instead.

提交回复
热议问题