Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 567
Mas Bagol Avatar asked Mar 28 '15 09:03

Mas Bagol


People also ask

Why is cout not printing anything?

This may happen because std::cout is writing to output buffer which is waiting to be flushed. If no flushing occurs nothing will print. So you may have to flush the buffer manually by doing the following: std::cout.

Why does Std cout not work?

In a windowing system, the std::cout may not be implemented because there are windows and the OS doesn't know which one of your windows to output to. never ever give cout NULL.

How do you stop cout without a new line?

The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.


1 Answers

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.

like image 140
emlai Avatar answered Sep 29 '22 10:09

emlai