可以在所有cout已经写入控制台之前main()返回吗? [英] Can a main() return before all cout has been written to the consol?

查看:173
本文介绍了可以在所有cout已经写入控制台之前main()返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在一个调用C ++程序的R脚本中跟踪错误。 R告诉我,我的C ++返回了NA - 但是当我浏览该程序时似乎不是这样。没有什么调用会导致在R中的NA。因此我的问题,如果R可能永远不会捕获C ++程序的输出,因为在所有输出之前调用 return 0 已写入控制台。

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.

我的程序会将一些数字写入控制台。每行一个,最后一行以 endl 结尾。

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;
}

我的R脚本会这样做:

x <- as.numeric(system("./myProgram", intern=T))
if(any(is.na(x))) {
    stop("Wooppp, x is NA: ", x)
}


b $ b

可以,R不从程序获得cout输出?
此问题与相应的R问题相关:
DEOptim始终告诉:目标函数的NaN值

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

推荐答案

一般来说,有一部分输出尚未在main()结束之前刷新。但是,在程序结束时,任何东西都应该被刷新。

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.

更多的细节,main只是一个函数,对于程序员这是入口点程序,虽然实际上运行时在此调用之前/之后执行一些部分。这包括加载共享对象,调用全局变量的析构函数和一些其他的东西,你实际上应该不知道作为一个普通的程序员。关于

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.

由于std :: cout是一个全局对象,它将使用其析构函数刷新正确的数据。虽然大多数实现冲洗\\\
字符(不认为它需要),std :: endl和std :: flush(我认为这是必需的),这个例子应该是无论如何。

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.

我会尝试拆分这个问题,并尝试将C ++程序的输出推送到文件读取它(从相同的R程序),尝试控制台输入...

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 ...

这篇关于可以在所有cout已经写入控制台之前main()返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆