如何从cpp文件中传递一个命令行参数并在shell脚本中使用?

问题描述 投票:0回答:2

所以,我必须创建一个cpp文件,用我的脚本来搜索某人的名字。我是个新手,所以我知道的不多,但这是我目前所拥有的。另外,我必须使用system()。下面是我的代码

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

int main (int argc, char *argv[]) {
    system("./findName.sh" + argv[1] );
    return 0;
}
c++ command-line-arguments
2个回答
1
投票

问题是,在C++中,字符串字元(如 "./findName.sh")不是 std::string但是指针。对于指针来说,加法比字符串连接有另一种意义。

你可以创建一个 std::string 并用它来执行连接。

    std::string scriptName = "./findName.sh";
    std::string command = scriptName + " " + argv[1];

    system(command.c_str());

不要忘记检查 argc 以确保有一个论点。


0
投票

您可以使用 std::systemboost::process 为此,。

© www.soinside.com 2019 - 2024. All rights reserved.