Why / when is cout buffer automatically flushed? - c++

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.

Related

Design of a simple progress bar to cout goes from 0->100% instantly at the end in C++

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;

Weird output after inserting std::ends

If I write cout << "Hi!" << ends << "1234";, the 1 will disappear after a while. From C++ reference, I know that std::ends inserts a null character into the stream. But when does this insertion happen?
The full code is
#include <iostream>
int main(int argc, char** argv) {
std::cout << "Hi!" << std::ends << "1234";
return EXIT_SUCCESS;
}
Running the program shows Before
,after maybe 0.5 second, it becomes After.
As far as the language itself is concerned, all cout << ends does is write \0 to the stream. It does not close the stream or cause things to be unexpectedly re-ordered. For the avoidance of any doubt, in your case, the language guarantees that "Hi!" will be be buffered before \0 and that is buffered before "1234".
My understanding is that a terminal ought to silently ignore \0. (It should regard it as an NOP, i.e. no-operation, instruction), but some terminals interpret it, in error, as a space.
That appears to be happening in your case.

Printing array elements in one second intervals using sleep()

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).

Printing a character array

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.

unexpected behavior when read a character from istringstream

I have a question on the stream behavior, see the following example. What I was expecting is the ss_char and ss_int will be eof state, but just the ss_int will be eof state.
My question is, why isn't ss_char eof state?
Can't I use the operator>>, only the istringstream::get() function, but then why read the value successfully?
Output:
char value: a
int value: 42
ss_char eof: false // why false?
ss_int eof: true
Sorry for my poor English. I’m working on improving my English.
#include <iostream>
#include <sstream>
int main(int /*argc*/, char const * /*argv*/[])
{
char c;
int num;
std::istringstream ss_int("42");
std::istringstream ss_char("a");
if (ss_char >> c)
{
std::cout << "char value: " << c << std::endl;
}
else
{
std::cout << "cannot read char" << std::endl;
}
if (ss_int >> num)
{
std::cout << "int value: " << num << std::endl;
}
else
{
std::cout << "cannot read int" << std::endl;
}
std::cout << std::endl;
std::cout << "ss_char eof: " << std::boolalpha << ss_char.eof() << std::endl; // why false
std::cout << "ss_int eof: " << std::boolalpha << ss_int.eof() << std::endl;
return 0;
}
CppReference says: "This function only reports the stream state as set by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a get(), which returned the last byte of a file, eof() returns false. The next get() fails to read anything and sets the eofbit. Only then eof() returns true."
oefbit will turn true when a read operation attempts to read beyond end of file, but not when it reads exactly to the end of file without trying to go further. When you read the char, it knows it should read a single byte, so this read operation is ok, the read position advance 1 byte, goes to the end, but let say the the stream still haven't noticed that it is indeed the end, it will if you try to read something else. When you read an integer, it tries to read beyond 42 because the length of the integer is not clear, it could have been 42901, so it has to read until it sees an space, and end of line, or eventually the end of the file/stream if there's nothing else to read.
And the result of the operator >> is the stream itself. When it is converted to void* (or bool, depends on c++11 or previous) it works as !fail(), so it tells you if the read or write operation was ok, regardless of whether it reached the end of file (next read operation will fail if it is now at the end).
The EOF condition doesn't actually occur until you try to read past the end of the stream.
In the char case you read exactly one character, the only one available. You don't try to read past the end because there is no need to.
Extracting an int on the other hand attempts to consume as many digits as possible. It reads the 4 and the 2, and then it tries to read again to see if there is another digit to consume, it does attempt to read past the end in this case. It notices that the input came to an end and so finishes the conversion of 42.
when extracting chars, it will pull a single character at a time and skip white spaces on consecutive calls.
when extracting int, the parser attempts to pull as many characters out to form the number. this causes the integer extraction to hit the eof in your test case.