Automatic cout flushing
Asked Answered
C

2

7

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,

Cerebrospinal answered 13/6, 2012 at 17:14 Comment(2)
If this is an interactive program then it's good to flush manually anyway. std::cout << "Please enter two numbers to add. " << std::flushScorify
If the Java is sending the data, I don't think this is theoretically solvable in the general case, Note that you can do the same thing from a batch file: echo 2 & echo 3 & myprogram.exe <<<"2\n3 and it would look just the same. The problem here has nothing to do with flushing or buffering.Isaiah
M
7

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.

Misplay answered 5/3, 2015 at 22:20 Comment(0)
N
3

I can't guarantee that it will fix all of your problems, but to automatically flush the stream when you're couting you can use endl

e.g.:

cout << "Please enter two numbers to add: " << endl;

using "\n" doesn't flush the stream, like if you were doing:

cout << "Please enter two numbers to add:\n";

Keep in mind that using endl can be (relatively) slow if you're doing a lot of outputting

See this question for more info

Ninebark answered 13/6, 2012 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.