运行外部程序并获得返回的整数

running external program and obtaining returned integer

本文关键字:返回 整数 外部 程序 运行      更新时间:2023-10-16

我有以下MWE,它返回一个整数:

#include <iostream>
using namespace std;
int main()
{
    int a = 2;
    return a;
}

现在,我想通过Windows中的命令行(CMD)调用此程序。这是我如何做的程序:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
    int a = system("c:test_batch.exe");
    cout << a << endl;
    return 0;
}

但是,这不会返回值2,而是0。我不明白这一点,因为我认为系统返回程序的出口代码,在这种情况下为2。

系统返回命令interpeter返回的值,而不是由实际命令。

您需要做

之类的事情
int a = system("c:test_batch.exe && exit %ERRORLEVEL%");