C++程序执行另一个带有命令行参数的程序

C++ Program to execute another Program with Command line arguments

本文关键字:程序 命令行 参数 执行 另一个 C++      更新时间:2023-10-16

如何使用c++程序中的参数执行命令行程序?这就是我在网上发现的:

http://www.cplusplus.com/forum/general/15794/

std::stringstream stream;
stream <<"program.exe "<<cusip;
system(stream.str().c_str());

但它似乎不接受实际的程序位置,所以我不确定如何应用它。我希望有这样的东西:

std::stringstream stream;
stream <<"C:TestsSO QuestionbinReleaseHelloWorld.exe "<<"myargument";
system(stream.str().c_str());

这会给出几个与反斜杠相关的警告,并且程序无法运行。它希望你把这个程序放在某个特定的地方吗?

这是我在控制台中得到的输出:

"C:\Tests"未被识别为内部或外部命令,可操作程序或批处理文件。

附录:

因此,根据Jon的回答,我的正确版本如下:

#include <iostream>
#include <cstdlib>
#include <sstream>
#include <cstring>
int main(int argc, char *argv[])
{
std::stringstream stream;    
stream << ""C:\Tests\SO Question\bin\Release\HelloWorld.exe""
       << " " // don't forget a space between the path and the arguments
       << "myargument";
system(stream.str().c_str());
return 0;
}

首先,只要希望实际字符串值中出现一个反斜杠,就应该在文字字符串中使用反斜杠。这是根据语言语法;一致性编译器可能比简单地警告更糟糕。

在任何情况下,您遇到的问题都是由于在Windows中包含空格的路径必须用双引号括起来。由于双引号本身需要在C++字符串文本中转义,因此需要编写

stream << ""C:\Tests\SO Question\bin\Release\HelloWorld.exe""
       << " " // don't forget a space between the path and the arguments
       << "myargument";

这给出了几个与反斜杠相关的警告

我相信是C++中的转义字符,使用\可能会解决这个问题。