Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with C++ console output

Tags:

c++

c

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

like image 411
Artem Ohanjanyan Avatar asked Aug 09 '13 20:08

Artem Ohanjanyan


2 Answers

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.

like image 118
Eugene Avatar answered Sep 28 '22 08:09

Eugene


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.

like image 24
Guvante Avatar answered Sep 28 '22 08:09

Guvante