Sublime Forum

Dynamic printing in infinite loop

#1

Hellow :slight_smile:

I wrote this little piece of code :

int main()
{
while (1)
{
std::cout << “yay”;
sf::sleep(sf::seconds(2));
}
return 0;
}

As all the ouputs in console are printed when the main program is finished -which never happen, in my case- I see no output. Is there a way to configure ST so the outputs would be printed dynamically, while the loop is running ?

Thanks :slight_smile:

0 Likes

Simple while True loop freezes sublime completely?
How to get build output in real-time?
#2

Based on my (simplistic) text on my Linux machine, stream buffering may be doing you favours you don’t want it to.

For example, this outputs “yay” to the console once a second and you can see the text appearing in the build panel while it happens:

#include <stdio.h>
#include <unistd.h>

int main ()
{
    while (1)
    {
        printf ("yay");
        fflush (stdout);
        sleep (1);
    }
}

Commenting out the fflush stops it from working. Or if you will, based on this test it IS working, but you need to wait for enough output to be generated to fill the stream buffer so that it gets written out (and thus picked up by Sublime). Assuming a buffer of 64k, the loop needs to run 21,845 times to fill the buffer, and at 2 seconds per output you just need to wait 12 hours or so. :wink:

So, something like cout << "yay" << flush; should make your code work, assuming I’m remembering exactly how that works in C++ (it’s been a while).

3 Likes

#3

Hi,

Thanks for your answer. cout << “yay” << flush works great indeed, and there was actually another way to make it work : cout << “yay” << std::endl. Seems new line forces the buffer to print :slight_smile:

Thanks !

1 Like

#4

Yes, line buffering is usually the default for file handles that are connected to something interactive (like a terminal).

1 Like