It's probably a long-shot that anyone can answer this without seeing all the source code and libraries, etc., but I'll try.
I have a program X written in C++ using boost-1.41. If X outputs with std::cout, then running X from another program using fp=popen("X", "r") allows X's output to be seen via fgets(buff, 1024, fp).
Now if I change X to use printf() instead of std::cout, the output of X is no longer seen. However, running X from bash produces the output as expected.
What could possibly explain this difference?! I suspect boost is involved here, but I don't know much about boost.
Note: I am happy sticking to std::cout and my problem is solved. But I'm trying to understand what the problem was with printf().
The reason is that you probably used std::endl with std::cout. That, in addition to writing a newline character, also flushes the output buffer.
To do the same with printf you can just add fflush(stdout); after the call.
Related
I try to track down an error in a R-script that does call a C++ program. The R tells me, that my C++ returned NA - but that does not seems to be the case when I look through the program. There is nothing called that would result in NA in R. Hence my question, if R may never capture the output from the C++ program, because return 0 is called before all output has been written to the console.
My program does writes some numbers to the console. One number per line, the last line ends with endl.
main()
{
cout<<33.12<<"\n"; //print a couple of number to cout
cout<<9711.3<<"\n"<<5699.14<<endl;
return 0;
}
My R-Script does stuff like this:
x <- as.numeric(system("./myProgram", intern=T))
if(any(is.na(x))) {
stop("Wooppp, x is NA: ", x)
}
Can it be, that R does not get the cout-output from by program?
This question is related to the corresponding R-question:
DEOptim keeps telling: NaN value of objective function
In general, yes, it would be possible to have part of the output not yet flushed before the end of main(). However, by the end of the program, everything should be flushed anyhow.
Some more detail, main is just a function, for the programmer this is the entry point of the program, though actually the runtime does some parts before/after this call. This includes loading shared objects, calling destructors of global variables and some other stuff you actually shouldn't know anything about as a regular programmer.
As std::cout is a global object, it will use its destructor to flush the right data. Though as most implementations flush on the "\n" character (don't think it is needed), std::endl and std::flush (I thought this was required), this example should be fine anyhow.
I would try splitting this issue, and try pushing the output of the C++ program to file to read it afterwards (both from the same R-program), try console input ...
Flush happens in the following cases:
std::cerr
std::cin
program termination
in many implementations, standard output is line-buffered, meaning "\n" flushes anyway
So it seems in most regular programs, std::endl is basically unnecessary, but it's used almost everywhere.
std::cerr
But what if I do not want to write to stderr, but rather stdout?
std::cin
But what if I just want to give the user some status update and do not want any input?
program termination
As above, what if I want to tell the user something before the program is done?
in many implementations, standard output is line-buffered, meaning "\n" flushes anyway
But what about the platforms that don't? Regardless of whether or not such a platform currently exists, I want my code to work as intended as defined by the standard, not as by "meh, will probably be fine on all implementations".
If all of the above apply (the fourth point actually always applies), you need to flush "by hand". If the flush gets handled by one of the first three, you don't.
So it seems in most regular programs, std::endl is basically unnecessary, but it's used almost everywhere.
No it's not redundant, since implementation of flushing along '\n' isn't mandated by the standard. That's just an implementation specific behavior, while the behavior of std::endl is always clearly defined.
As the title suggests, I'm looking for a way to have cout 'flush' itself only when I explicitly tell it to. I know this can be achieved by 'buffering' the contents we want to write into a string or a stringstream, but I'm looking for the most efficient way of doing this.
Also it would be nice to also be able to eat up trailing newlines in this buffer. I've seen solutions that writes \b to cout; however I'm pretty sure this is unreliable due to flushing (correct me if I'm wrong).
Without using stringstream, your best bet it so prevent the two most common ways that lead to an automatic flush: when you are outputting something and when you explicitly call << std::endl. You can deactivate the first by setting the unitbuf flag of std::ios_base::fmtflags. This, though, won't likely stop the automatic flush when a new line is encountered. If your OS decides it needs to flush at every \n character, there's nothing you can do (on the standard C++ side).
Therefore I'd recommend manual buffering.
I am writing a program for school, and want to include an Easter Egg with the look of disapproval (ಠ_ಠ), however, I do not know what classes in C++ support this character. I would assume this character be included in unicode, but I am not sure how to use that to output into a console application.
If anyone could help me out with this, I would appreciate it. Thanks
Well you need to enable Unicode for your application.
For MSVC you can use _setmode(_fileno(stdout), _O_U16TEXT); at the start of your main.
But for mingw this is a bit more difficult, see here.
To actually print it you can use the character code and use wcout but be wary!
From: http://www.cplusplus.com/reference/iostream/cout/
A program should not mix output operations on cout with output operations on wcout (or with other wide-oriented output operations on stdout): Once an output operation has been performed on either, the standard output stream acquires an orientation (either narrow or wide) that can only be safely changed by calling freopen on stdout.
You can use \u0CA0, that's the Unicode code for this eye thing. Here's a live example:
int main() {
cout << "hi \u0CA0_\u0CA0";
return 0;
}
https://ideone.com/QBFtsM
Although IDEOne supports unicode (as in, I can just paste ಠ) so I'm not sure if that will work for you. Let me know.
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end.
I don't quite understand why this flush operation is needed.
Anyone have any insight?
To add to the other answers: your debugging statements should instead go to cerr, because:
it writes to the standard error, which means that, running the application, you can easily separate the "normal" program output from the errors/debug information via redirection;
most importantly, cerr by default is unbuffered, which means that, after each output operation, it will automatically flush itself, and in general this is desirable for errors and debug output.
(source: C++ standard, §27.3.1 ¶4-5, §27.4.2.1.2 table 83)
Are you using std::endl to terminate your lines. This should be the
usual practice, until performance issues require otherwise, but for some
reason, I see a lot of code which uses '\n' instead.
Otherwise, you can always do:
std::cout.setf( std::ios_base::unitbuf );
as one of the first things in main. This will cause a flush at the
end of every <<, which is more than you need, but for diagnostic
output to the console, is probably quite acceptable.
Is the data that isn't automatically getting flushed lacking a \n at the end? By default, standard out doesn't get delivered until a carriage return is seen.
"When you send output to a stream, it does not necessarily get printed immediately. Rather, it may wait in a buffer until some unspecified event, e.g. buffer full enough, reading from input, or exit from program. The details may vary."
http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200109/notes/io.html
It is the right behavior. You probably use std::endl that add \n and flush the buffer. http://www.cplusplus.com/reference/ostream/endl/
You need to flush the stream, if you want to see the output.
The answer of std::endl is only valid if you want a return.
Not sure how you would do this if you wanted to flush a command prompt out.
In C++ you can use endl formatter with cout operator rather then flush.