问题
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
回答1:
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 ...
来源:https://stackoverflow.com/questions/35731217/can-a-main-return-before-all-cout-has-been-written-to-the-consol