Calls to flush cout are ineffective

Tyler picture Tyler · Oct 21, 2013 · Viewed 9.5k times · Source

I am attempting to have the cout buffer flush to view a string before I manipulate it. Ive attempted to flush the buffer with calls to both std::flush() and std::cout.flush() but neither actually flush my output.

Only a call to std::endl has successfully flushed the buffer for me.

Here is my code

std::istringstream stm (game.date());
int day, month, year;
char delim = '/';

std::cout << "Date before: " << game.date() << std::flush; // first flush attempt
std::cout.flush();  // second flush attempt doesnt work
//std::cout << std::endl;   // if this is executed the buffer will flush

// Split date string into integers for comparison
stm >> month >> delim;
stm >> day >> delim;
stm >> year >> delim;

std::cout << "Date after: " << " | " << month << "/" << day << "/" << year << std::endl;

Here is my output
Date after: | 1/31/13
Date after: | 3/21/12
Date after: | 11/11/11
Date after: | 10/1/10
Date after: | 1/2/12

So as you can see the first call to cout isnt ever flushed but as I said before the buffer will successfully flush with endl, which calls flush itself. I am currently running Ubuntu 12.04 with VirtualBox on my host macbook pro running Mountain Lion.

Is there anything I may be doing wrong in my flush calls or is this potentially a system issue?

Answer

Dietmar K&#252;hl picture Dietmar Kühl · Oct 21, 2013

Both std::cout << flush; and std::cout.flush(); will flush std::cout.

It looks as if your code inserts a carriage return (\r) into the stream. Assuming you print this year, it seems you insert it as a char with value 13 which happens to be \r. The upshot of this is that your later output will just overwrite the output as it will be on the same line. You can verify this by explicitly inserting a newline (\n) before flushing the stream.