Error C ++ console release

#include <iostream> using namespace std; int main() { cout << 1; while (true); return 0; } 

I thought this program should print 1 and then hang. But he doesn't print anything, he just hangs. cout << endl or cout.flush() can solve this problem, but I still want to know why it does not work as expected :) This problem arose during the codeforces contest, and I spent a lot of time studying the strange behavior of my program. It was wrong, it also hung, hidden output was actually debugging information.

I tried using printf (compiling with gcc) and it behaves the same as cout , so this question can also be attributed to C.

+6
source share
3 answers

You are writing a buffer. You need to flush the buffer. As mentioned in @Guvante, use cout.flush() or fflush(stdout) for printf.

Update:

It looks like fflush working with cout. But do not do this - in all cases this may not be the case.

+8
source

This is because cout outputs buffers. You must discard the buffer to actually print it. A.

endl and flush() do this cleanup.

Also note that your program freezes because you have an infinite loop ( while(true); ).

The reason this is done is because if you print a lot of data (for example, 1000 numbers), it can do this much more efficiently. In addition, most of the minor data points end in endl , since you want your output to span multiple lines.

+2
source

Regarding printf , the same thing is done as cout : you print to the buffer, you need to fflush(stdout); it with fflush(stdout); . Termination will clear the buffer, so you can see the result without your infinite loop.

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

+1
source

Source: https://habr.com/ru/post/951420/


All Articles