Buffered and unbuffered stream

前端 未结 5 717
迷失自我
迷失自我 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:38

    1) what do they mean by "the buffer is full".

    With buffered output there's a region of memory, called a buffer, where the stuff you write out is stored before it is actually written to the output. When you say cout << "hi" the string is probably only copied into that buffer and not written out. cout usually waits until that memory has been filled up before it actually starts writing things out.

    The reason for this is because usually the process of starting to actually write data is slow, and so if you do that for every character you get terrible performance. A buffer is used so that the program only has to do that infrequently and you get much better performance.

    2) it said in my book that everything sent to cerr is written to the standard error device immediatly, does this mean it send 'h' and then 'i'...?

    It just means that no buffer is used. cerr might still send 'h' and 'i' at the same time since it already has both of them.

    3)in this example ch will be assigned to "hello" and "world" will be ignored does it mean that it still in the buffer and it will affect the results of future statements ?

    This doesn't really have anything to do with buffering. the operator >> for char* is defined to read until it sees whitespace, so it stops at the space between "hello" and "world". But yes, the next time you read you will get "world".

    (although if that code isn't just a paraphrase of the actuall code then it has undefined behavior because you're reading the text into an undefined memory location. Instead you should do:

    std::string s;
    cin >> s;
    

    )

提交回复
热议问题