繁体   English   中英

捕获与 PHP exec() 分开的输出参数

[英]Capture output arguments as separate from PHP exec()

我有一个简单的 C++ 程序,我想通过函数 exec() 用 PHP 执行,我想单独捕获输出变量,以便我可以在 PHP 中执行进一步的计算。 我正在使用 g++ (GCC) 4.8.1 来编译程序。

C++代码:

#include<iostream>
#include<string>
using namespace std;

int main() {
    string test = "This is a test string";
    int n1=3, n2=4, n3=5;
    cout<<test<<n1<<n2<<n3;
    return 0;
}

PHP代码:

<?php
    $dir = getcwd();
    $command = "g++ ".$dir."\\files\\index.cpp -o ".$dir."\\files\\output.out";
    exec($command, $asdf);
    exec($dir."\\files\\output.out", $test);

    print_r($test);
?>

我得到的输出是:

Array ( [0] => This is a test string345 ) 

我想要的输出是:

Array ( [0] => This is a test string [1] => 3 [2] => 4 [3] => 5 ) 

这可以通过更改 C++ 代码中的以下行来实现:

cout<<test<<endl<<n1<<endl<<n2<<endl<<n3;

是否可以在每个变量之间不添加换行符的情况下获得相同的结果? 可以以某种方式捕获变量吗?

不知何故,您需要分隔输出,如果您不想使用换行符,一种方法是定义分隔符。 您需要确保您没有在其他任何地方使用分隔符。

例如,如果分隔符是:“#!#!#”

在 C++ 中更改以下代码

cout<<test<<n1<<n2<<n3;

到:

String sep = "#!#!#";
cout<<test<<sep<<n1<<sep<<n2<<sep<<n3;

并在 php 中获取输出:

print_r( explode ("#!#!#", $test);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM