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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With