6

I don't know if it's related to flush in ostream. Since, endl is end with flush right? I don't know what is flush and how it works.

I have a function that will print out each characters of string every second. I want to print it out whitout new line after every characters. Then, I write this function:

using namespace std;

void print_char_per_second (string text) {                                           
    int i = 0;
    int len = static_cast<int>(text.length());
    while (i < len) {
        int tick = clock() % CLOCKS_PER_SEC;
        if (tick == 0) {
            cout << text[i];
            i++;
        }
    }   
}

It prints the text one after while loop finished looping and prints all of characters in the text at once. Why this is happen?

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Mas Bagol
  • 4,377
  • 10
  • 44
  • 72
  • [Here](http://stackoverflow.com/questions/14105650/how-does-stdflush-work) is an answer which explainins how `flush` works. – rsht Mar 28 '15 at 09:48
  • 2
    Besides the flush problem, your code still does not necessarily print one character per second. The test `int tick = clock() % CLOCKS_PER_SEC; if (tick == 0)` is way too strict. You cant guarantee that each time you call `clock()`, the value returned is one larger than the previous call. – Lingxi Mar 28 '15 at 10:55

1 Answers1

14

Flushing makes sure all output written to the stream so far is shown on the console.

You can do std::cout << std::flush or std::cout.flush() after each output operation to make sure the output is shown on the console immediately.

Right now it's just writing everything to the stream and only flushing the stream after the loop.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157