使用命令行参数执行另一个程序的C++程序

Ste*_*010 7 c++ command-line command command-line-arguments

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

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

std::stringstream stream;
stream <<"program.exe "<<cusip;
system(stream.str().c_str());
Run Code Online (Sandbox Code Playgroud)

但它似乎不接受实际的程序位置,所以我不知道如何应用它.我希望有这样的事情:

std::stringstream stream;
stream <<"C:\Tests\SO Question\bin\Release\HelloWorld.exe "<<"myargument";
system(stream.str().c_str());
Run Code Online (Sandbox Code Playgroud)

这给出了与反斜杠相关的几个警告 - 程序不起作用.是否期望您将程序放在某个特定位置?

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

"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;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 10

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

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

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


Flo*_*man 5

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

我相信\在C++中使用转义字符\\代替可能会解决这个问题.