Question

So, I have the program below. What it does is, it prints random numbers while formating them with a width of 10 on the console.

Now, when I added the sleep function, I expected it to print one number every 10 milliseconds (or more), but what it does is, it prints 100 outputs every 100*10 milliseconds. I was wondering, why does this happen? Does the output get buffered or what?

#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <iomanip>

int main()
{
    srand(time(0));
    for (int i = 1; i < 1000000; i++)
    {
        usleep(10*1000);    // No matter the input, the same thing happens
        cout << setw(10) << rand()%(90*i) + 10*i;
    }
}

I tried this both on windows and unix and it's the exact same thing.

Was it helpful?

Solution

Yes, the output does get buffered.

Use std::cout.flush(); to flush manually.

As a note, std::endl (appends a new line and) does the flush.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top