C ++ output buffer refresh

Source: Internet
Author: User

In c ++, io operations are implemented by io objects. Each io object manages a buffer to store data read and write by the program.

Only when the buffer is refreshed can the content in the buffer be written to a real file or output device.

Then, under what circumstances will the output buffer be refreshed? There are five situations:

1. The program ends normally. As part of the main return work, all output buffers are cleared.

2. When you are not sure, the buffer may be full. In this case, the buffer will be refreshed before the next value is written.

3. Refresh the buffer with the operator display, such as using endl.

4. After each output operation is completed, use the unitbuf operator to set the internal status of the stream to clear the buffer.

5. The output stream can be associated with the input stream. when reading the input stream, the associated output buffer is refreshed.

We can use the following instance code to deepen our understanding:


[Cpp]
// Operator
Cout <"hi! "<Flush; // flushes the buffer, adds no data
Cout <"hi! "<Ends; // inserts a null, then flushes the buffer
Cout <"hi! "<Endl; // inserts a newline, then flushes the buffer
 
// Unitbuf Operator
Cout <unitbuf <"first" <"second" <nounitbuf;
 
// Unitbuf refreshes the stream after each write operation.
 
// The preceding statement is equivalent
Cout <"first" <flush <"second" <flush;
 
// Nounitbuf restores the stream to normal in the system-managed buffer Mode
 
// Bind the input and output together
// The standard library has already bound cin and cout together.
// We can call tie () to implement binding.
Cin. tie (& cout); // the library ties cin and cout for us
Ostream * old_tie = cin. tie ();
Cin. tie (0); // break tie to cout, cout no longer flushed when cin is read
Cin. tie (& cerr); // ties cin and cerr, not necessarily a good idea!
Cin. tie (0); // break tie between cin and cerr
Cin. tie (old_tie); // restablish normal tie between cin and cout

 

By RO_wsy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.