Artem  Ohanjanyan
Artem Ohanjanyan

Reputation: 63

Issue with C++ console output

#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.

Upvotes: 6

Views: 1041

Answers (3)

Eugene
Eugene

Reputation: 9474

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.

Upvotes: 8

Zeta
Zeta

Reputation: 105886

Concerning printf, the same as cout holds: you're printing into a buffer, you need to flush it with fflush(stdout);. Termination will flush the buffer, this is why you can see the output without your infinite loop.

See Why does printf not flush after the call unless a newline is in the format string? for more information.

Upvotes: 1

Guvante
Guvante

Reputation: 19203

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.

Upvotes: 2

Related Questions