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