Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic cout flushing

Good day,

I wrote a Java program that starts multiple C++ written programs using the Process object and Runtime.exec() function calls. The C++ programs use cout and cin for their input and output. The Java program sends information and reads information from the C++ programs input stream and outputstream.

I then have a string buffer that builds what a typical interaction of the program would look like by appending to the string buffer the input and output of the C++ program. The problem is that all the input calls get appended and then all the output calls get posted. For example, and instance of the StringBuffer might be something like this...

2
3
Please enter two numbers to add. Your result is 5

when the program would look like this on a standard console

Please enter two numbers to add. 2
3
Your result is 5

The problem is that I am getting the order of the input and output all out of wack because unless the C++ program calls the cout.flush() function, the output does not get written before the input is given.

Is there a way to automatically flush the buffer so the C++ program does not have to worry about calling cout.flush()? Similiar to as if the C++ program was a standalone program interacting with the command console, the programmer doesn't always need the cout.flush(), the command console still outputs the data before the input.

Thank you,

like image 564
Matthew Avatar asked Jun 13 '12 17:06

Matthew


People also ask

Does cout auto flush?

It is an implementation detail, one that invariably depends on whether output is redirected. If it is not then flushing is automatic for the obvious reason, you expect to immediately see whatever you cout.

What is cout << flush?

The predefined streams cout and clog are flushed when input is requested from the predefined input stream (cin). The predefined stream cerr is flushed after each output operation. An output stream that is unit-buffered is flushed after each output operation.

What does STD flush do?

On a sequential stream syncing with the external destination just means that any buffered characters are immediately sent. That is, using std::flush causes the stream buffer to flush its output buffer. For example, when data is written to a console flushing causes the characters to appear at this point on the console.


1 Answers

In case someone comes looking for a way to set cout to always flush. Which can be totally fair when doing some coredump investigation or the like.

Have a look to std::unitbuf.

std::cout << std::unitbuf; 

At the beginning of the program.

It will flush at every insertion by default.

like image 64
Mario Corchero Avatar answered Sep 21 '22 02:09

Mario Corchero