Mas Bagol
Mas Bagol

Reputation: 4617

Cout won't print text without endl inside while loop?

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?

Upvotes: 7

Views: 8951

Answers (1)

Emil Laine
Emil Laine

Reputation: 42828

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.

Upvotes: 15

Related Questions