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

时间:2012-06-08 15:58:13

标签: c++ c

我有一个包含3个不同命令行命令的字符串数组。我试图学习如何将一个包含这些命令的字符串数组传递给for循环中的系统函数(或类似函数,即exec()),而不是写出3个系统函数。我无法弄清楚如何将此字符串数组一次传递到系统函数中。目标是获得每个退出状态并在返回错误时中断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 :(");
                }
            }   

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

system(arrString[i])

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

答案 2 :(得分:0)

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

system(arrString[i].c_str())