Auto flush cout

Good afternoon,

I wrote a Java program that runs several C ++ programs using the calls to the Process and Runtime.exec () functions. C ++ programs use cout and cin for input and output. The Java program sends information and reads information from the input stream of C ++ programs and the output stream.

Then I have a string buffer that builds what a typical program interaction would look like by adding C ++ program input and output to the string buffer. The problem is that all incoming calls are added and then all output calls are published. For example, an instance of StringBuffer might be something like this ...

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

when the program will look like this on a standard console

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

The problem is that I get the input order and the output of all from wack, because if the C ++ program does not call the cout.flush () function, the output is not written until the input is entered.

Is there a way to automatically flush the buffer so that the C ++ program does not bother calling cout.flush ()? Just as the C ++ program was a stand-alone program that interacts with the command console, the programmer does not always need cout.flush (), the management console still displays the data before entering.

Thanks,

+4
source share
2 answers

I can not guarantee that it will fix all your problems, but to automatically reset the stream when you cout ing, you can use endl

eg:.

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

using "\n" does not clear the stream, as if you were doing:

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

Keep in mind that using endl can be (relatively) slow if you draw a lot of output

See this question for more information.

+2
source

In case someone is looking for a way to set cout to always hide. Which can be absolutely fair when conducting any kind of investigation coredump or the like.

Take a look at std::unitbuf .

 std::cout << std::unitbuf; 

At the beginning of the program.

It will load by default with every installation.

+2
source

All Articles