I see developers on web generally use:
but they sometimes use flush:Code:std::cout << msg;
What is the purpose of the std::flush? In which cases it is recommended to use?Code:std::cout << msg << std::flush;
Cheers
I see developers on web generally use:
but they sometimes use flush:Code:std::cout << msg;
What is the purpose of the std::flush? In which cases it is recommended to use?Code:std::cout << msg << std::flush;
Cheers
It's recommended when you want your output to immediately appear on the screen, rather than whenever the stream chooses to flush on its own. One important application is in a multithreaded program, where multiple threads may write to standard output, and you want a given thread's output to appear together. You'd use a combination of locking and flushing the stream.
What can this strange device be?
When I touch it, it gives forth a sound
It's got wires that vibrate and give music
What can this thing be that I found?
To expand a little, I/O is typically buffered because it's slow. Therefore, what you write may not immediately appear on screen.
So in order to guarantee that you see what you want to write, you want to flush to stream. By doing this, you force whatever is stored in the buffer to be sent to the screen. Flushing is done by std::flush.
It should be also pointed out that std::endl, which outputs newline character, also flushes the stream. (To avoid flushing when inserting a newline character, one has to explicitly insert '\n' instead of std::endl).