将字符串数组传递给系统函数

Passing a string array to system function?

本文关键字:系统 函数 字符串 数组      更新时间:2023-10-16

我有一个包含 3 个不同命令行命令的字符串数组。我没有写出 3 个系统函数,而是在尝试学习如何在 for 循环中将这些命令传递给系统函数(或类似的函数,即 exec())。我在尝试弄清楚如何将此字符串数组一次传递到系统函数中时遇到麻烦。目标是获取每个的退出状态,并在返回错误时中断 for 循环。

            std::string arrString[3] = {"something","another thing","a final thing"}
            int i;
            for(i=0; i<3; i++)
            {
                if (system(/*Something*/))
                ;//Do something...
            }     

编辑:这输出发生了错误,但不应该。

                std::string arrString[4] = {"cmd","cmd","cmd"};
            int i;
            for(i=0; i<3; i++)
            {
                if (system(arrString[i].c_str())==0) {
                    OutputDebugStringW(L"It works!");
                }
                else
                {
                    OutputDebugStringW(L"It doesnt work :(");
                }
            }   

system需要char*,所以你需要对数组的每个元素调用c_str

std::string arrString[3] = {"something","another thing","a final thing"}
int i;
for(i=0; i<3; i++) {
    if (system(arrString[i].c_str())) {
        //Do something...
    }
}
system(arrString[i])

然后检查退出代码并在适当时中断循环。

您必须先使用 c_str() 函数将std:string转换为char*

system(arrString[i].c_str())