2

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.

ShadoWalkeR
  • 123
  • 1
  • 8
  • 2
    Yes, the output does get buffered. Either explicitly `flush()` or `<< std::endl;`. – hmjd Feb 21 '14 at 11:13
  • @hmjd So, when after collecting 102 outputs the system decides to ouput? When I add `<< endl;` every number gets printed correctly, but on a new line. How would I go about printing it the same way but formatted?(Every number on its own, in the same line) – ShadoWalkeR Feb 21 '14 at 11:20
  • `std::cout.flush()` will avoid the newline. – hmjd Feb 21 '14 at 11:23
  • OK, I solved it by adding `cout.flush();` after printing. Works perfectly. – ShadoWalkeR Feb 21 '14 at 11:23

1 Answers1

0

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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302