Search code examples
c++qtstdqtcore

Qt -" \n" doesn't work, but std::endl does?


I have a rather strange problem that I've never encountered before and I have no idea what is causing it. I'm working in Qt 4.7, and I have a lot of things in my project that print to the terminal. These prints are all triggered by one button press. However, when I press the button, they don't all print. Instead, all the print statements that end with << std::endl; will print, but the first one that ends with "random text...\n"; won't, and none of the ones after that will either regardless of which style they use. If I hit the button again to run the entire thing again, it will then print the remaining statements, followed by the same initial output as last time. I could just make them all std::endl, but there's a lot of them, so I'd really rather not. I've never seen anything like this before, does anyone have any advice for how to fix it? Thanks!

EDIT: As per request, this is the syntax (assuming there's a button call mybutton on the UI)

void on_mybutton_pressed()
{
std::cout << "A" << std::endl;
std::cout << "B" << std::endl;
std::cout << "C\n";
}

Output after first time button is pressed:

A
B

Output after second press:
C
A
B


Solution

  • You can enable unit buffering for cout at the beginning of your program if you really want to:

    std::cout << std::unitbuf;
    

    This will flush the buffer after every output operation.

    In your situation, I'd consider this a bit of a hack rather than a solution though. There are performance penalties associated with flushing (though they do not matter if you don't print at high frequencies).