#include <iostream>
using namespace std;
int main()
{
cout << 1;
while (true);
return 0;
}
I thought that this program should print 1 and then hung. But it doesn't print anything, it just hungs.
cout << endl
or cout.flush()
can solve this problem, but I still want to know why it's not working as expected :)
This problem appeared during codeforces contest and I spent a lot of time on looking at strange behavior of my program. It was incorrect, it also hunged, hidden output was actually debug information.
I tried using printf
(compiling with gcc) and it behaves as well as cout
, so this question can be referred to C also.
You writing to a buffer. You need to flush the buffer. As @Guvante mentioned, use cout.flush()
or fflush(stdout)
for printf.
Update:
Looks like fflush
actually works with cout. But don't do that - it may not be the fact in all cases.
That is because cout
buffers output. You have to flush the buffer for it to actually print.
endl
and flush()
both perform this flushing.
Also note that your program hangs because you have an infinite loop (while(true);
).
The reason it does this is so that if you are printing a lot of data (say 1000 numbers) it can do so drastically more efficiently. Additionally most minor data points end with endl
anyway, since you want your output to span multiple lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With