DEV Community

loading...

std::cout is not printing in console/terminal

lucpattyn profile image Mukit, Ataul ・1 min read

Suppose in a C++ program, you are doing this but nothing appears in the console or terminal window.

std::cout << "running 1 ..";

This may happen because std::cout is writing to output buffer which is waiting to be flushed.
If no flushing occurs nothing will print.

So you may have to flush the buffer manually by doing the following:

        std::cout.flush();

However, if you call std::endl at the end, then it will invoke the flush, so you wouldn't have to call it manually.

If you write std::cout << "running 1 .." << std::endl;

You would see output is now showing in the console or terminal window.

Thanks https://dev.to/cnskn for pointing it out.

Discussion (7)

Collapse
cnskn profile image
cnskn

Hello,
Never experience this problem, but what is even more odd is that endl do call flush as well (check en.cppreference.com/w/cpp/io/manip...)

I'm wandering what compiler/std/OS you used?

Collapse
lucpattyn profile image
Mukit, Ataul Author

Thanks, i actually forgot the endl in the program :) .

then used cout.flush() and when it started working i added the endl again.

Thanks for correcting this tip :)

Collapse
lucpattyn profile image
Mukit, Ataul Author

Mac OSX and gcc/g++ compiler.

Collapse
linuxrocks2000 profile image
LinuxRocks2000

What about with std::thread? I am trying to output from a thread using std::flush, but it doesn't print. Even stranger, if I remove the call to std::flush, recompile and run (no output), then add it again, recompile, and run it prints out the output from the last iteration, but not the new output.

Collapse
linuxrocks2000 profile image
LinuxRocks2000

I figured out my issue - the thread never deatched or joined. On a completely unrelated note, is it considered bad programming to have an infinite while loop in a thread?

Collapse
lucpattyn profile image
Mukit, Ataul Author

If your thread doesn't go to sleep mode because of waiting for I/O or probably waiting for a result, then
definitely you have to put a sleep to make sure the thread doesn't hog the cpu.
You can have a 50ms or 100ms (millisecond) sleep time when you are executing the infinite loop.

However, there are certain OS calls which automatically puts the thread to sleep mode to be activate later, in that case putting a manual sleep is not necessary.

Depending on the situation, having an infinite loop in a thread is not a bad thing, as long as you ensure you send the thread a message through an event or setting off a variable to quit when the main program quits.

Collapse
lucpattyn profile image
Mukit, Ataul Author

Sometimes it can happen for memory issues/pointer problems.
Maybe instead of printing in the thread, you can try to use a queue and print in the main thread from that queue just for testing.

Forem Open with the Forem app