Reputation: 3956
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,
Upvotes: 7
Views: 5107
Reputation: 5575
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.
Upvotes: 7
Reputation: 5599
I can't guarantee that it will fix all of your problems, but to automatically flush the stream when you're cout
ing 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
Upvotes: 3