I have an array that contains chars.
I am trying to print out an element once every second.
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
sleep(1);
i++;
}
This for some reason just waits for 110 seconds and than prints out the whole array at once.
But if i add a new line after every element it works just fine
int i=0;
while (i< 110)
{
cout << arrayValue[i]<<"\0";
cout<< endl;
sleep(1);
i++;
}
Any recommendation on how to get each element to print chronologically without having to make a newline?
This for some reason just waits for 110 seconds and than prints out the whole array at once.
Actually it doesn't, but your output is buffered. There is buffering in the C++ stream object, in the OS data pipe, and in your terminal.
Your stream thinks it would be a waste of resources passing characters through one at a time, and it's kind of right: the stream doesn't know you have a second to wait in between each one.
You don't need the newline, though; you can basically force a flush like so:
std::cout << std::flush;
Recall that std::cout << std::endl is equivalent to std::cout << '\n' << std::flush, and it's the '\n' part that you don't want.
This is usually enough but you may also need to reconfigure your terminal to turn off line buffering. (That's unlikely for output but quite common for input).
Related
I understand from here that if i were to output characters without flushing the buffer ( with endl or cin ) they wouldn't appear on my console until the program ends.
So i tried to make an infinite loop:
for(;;)
{
std::cout << "a" << std::endl;
}
and the same without flushing the buffer:
for(;;)
{
std::cout << "a";
}
They both output forever a, the only difference i can observe is that the latter version of code has some delay time before it starts outputting the letter. The first one starts immediately.
I was expecting the second one to output the chars only if there was a break in the loop, and the program would be terminated.
You are correct that std::endl, or the use of std::cin, causes a flush to occur, and the contents to be immediately output. std::endl is the equivalent of std::cout.put('\n'); std::cout.flush();, where as std::cin and std::cerr are tie()d to std::cout and therefore any operation to either of those executes std::cout.flush() for you.
However, in the second case, std::cout still has an underlying output sequence (an std::streambuf), which is a specified size. Once this buffer is full, the stream is flushed automatically, and you get the output to the console. Filling up this buffer is what you are seeing with the delay time you mentioned.
I would like to make a very basic progress indicator by printing an 'X' char to cout every time a loop progresses another 10%. I am trying to do this as shown in the code pasted below, but it doesn't seem to be working - when really it seems it should.
It's supposed to display steady progress throughout the loop, but instead I get all the X's coming at once after the loop has finished. This is not because the loops are completed too quickly for me to perceive. To verify this you can add an extra 'F' to "TOTAL" to increase the duration of the looping substantially, and you'll see it's not just a question of perception.
Any ideas what might be causing this?
#include <iostream>
#define TOTAL 0xFFFFFFF
using namespace std;
int main(void) {
//Make a counter for counting loops
double counter = 0;
// Set it to trigger after each 10% of progress
double counterMax = TOTAL / 10;
cout << "Starting now..." << endl;
for (double i = 0; i < TOTAL; i++) {
// Do something... anything
i++;
i--;
// Increment the counter
counter++;
// Print an X when the counter exceeds the 10%
// trigger point, and then reset the counter.
if (counter > counterMax) {
cout << 'X';
counter = 0;
}
}
cout << endl << "Done!";
return 0;
}
System input/output calls are usually slow operations. To increase the efficiency of programs, input and output streams are often buffered, to reduce the number of calls to the operating system.
When a program needs "non-buffered" output, one solution is to use the buffered output functions, and simple "flush" the output to ensure the operating system processes any output which has been queued in any buffers.
When the output buffer is filled, or when the stream is closed, it is automatically flushed. The standard output is also automatically flushed by certain sequences, like endl. But you can trigger a flush of the standard output at any point by called cout.flush() or by using the flush manipulator, like:
cout << 'X' << flush;
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?
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.
I have a function print_string which takes in a character array as its argument.
For some reason I can't get it to print out if I use a while loop like
int i = 0;
while(str[i]!= '\0'){
cout << str[i];
i++;
}
but if I use a for loop and specify the length of the array it can.
Thanks
The code works for me. My guess: you're probably experience the problem with buffering. std::cout is buffered, so characters first go into buffer, and then, at certain points, the contents of the buffer are put on screen.
The most typical way to force this is: std::cout << std::endl;
Also, tip: std::cerr is unbuffered, so you could use it for debugging this issue.
I'm trying to implement a "timer" function in C++ for the program to do something after some seconds.
However, I've got unexpected results.
short e, sum;
clock_t start;
double duration=0;
for (e=0; e<4; e++) {
start = clock();
while (duration < 1) {
duration = (clock() - start)/(double)CLOCKS_PER_SEC;
}
cout << duration;
duration = 0;
sum += e;
/* Calculate EPOCH error */
cout << e;
}
cout << "\n" << e<< "\n";
The results I expect are:
console output every second, followed by e (0,1,2,3)
at the end of the execution I expect sum to be 0+1+2+3 = 6,
Results obtained:
console output followed by e, all together when execution finishes
sum = 6
What I find uncertain is, why do the program prints to console until execution is finished and not every second as expected?
Cheers,
Your problem is that the output stream isn't flushed during your loop. Actually writing pieces of text to the console is somewhat expensive. Therefore the input is buffered and only written to the console when a flush occurs. Flushing the stream can be accomplished by streaming std::flush:
cout << e<<std::flush;
std::endl will also flush the stream in addition to adding a newline (writing \n might also do it, but that's not guaranteed).
As a sidenote: you might want to consider adding some sort of seperators between your numbers to make the output readable.