'Why does sleep() block std::ostream [duplicate]
Given the following:
const char opn[8] = { 0x16, 'O', 'P', 'N', 0x17, 0xa8, 0xa9, '\0' };
std::cout << opn;
sleep(5);
The string will only be written to cout after five seconds. The expected behavior would be for it to print the message to cout, and then wait for seconds.
Why does this happen?
Solution 1:[1]
std::cout is buffered by default, so the message won't be printed immediately but only when std::cout's buffer is flushed, i.e., when the program terminates.
Use
std::cout << opn << std::flush;
As @RemyLebeau stated in the comments to this answer, << std::endl is equivalent to << '\n' << std::flush; and also flushes the buffer.
Furthermore, you are missing the trailing null byte, so your program is undefined anyway as of now.
Solution 2:[2]
Output is normally buffered, so it won't come out until the buffer is full or the file is closed. You need to manually flush the output; e.g.:
std::cout << i << " " << std::flush;
If you wanted a line break to be inserted, you could use std::endl, which both inserts a line break and flushes the stream:
std::cout << i << " " << std::endl;
Solution 3:[3]
cout is buffered so it is saving the in-between things you are printing and printing them all at once when it flushes.
You can either add << std::endl; to the line that prints i or otherwise flush the buffer manually.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Remy Lebeau |
| Solution 2 | Cody Gray |
| Solution 3 | Guvante |
