【问题标题】:C++ Program to execute another Program with Command line arguments使用命令行参数执行另一个程序的 C++ 程序
【发布时间】:2013-01-27 02:58:42
【问题描述】:

如何使用来自 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:\Tests\SO Question\bin\Release\HelloWorld.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;
}

【问题讨论】:

  • 知道如何将标准输出从 system(...) 重定向到 std::string 或 std::stringstream?
  • @Pupsik 系统函数返回一个 int。显然,您需要知道您使用的任何操作系统的状态代码:“如果 command 不是空指针,则返回的值取决于系统和库实现,但通常预计是由调用命令,如果支持的话。” - 来自cplusplus.com/reference/cstdlib/system - 然后您可以根据返回的 int 生成正确的错误消息。
  • @Pupsik 不,我正在和其他 Pupsik 交谈。约翰尼·普普西克。他来自爱尔兰。
  • PS:C++ 实际上有一个 + 运算符用于连接字符串 - 示例 v.1:string myString = "something"; myString += "something else"; 或 v.2:直接但使用类型转换 string my = (string)"something" + " " +"something else"; 要点是: i> 您不必为此使用其他库...
  • 在这样的程序中,您可能希望返回退出值HelloWorld.exe,而不是零。也就是说,将最后两条语句替换为:return system(stream.str().c_str());

标签: c++ command-line command command-line-arguments


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 另外,您的代码将传递字符串“myarguments”,而不是包含此信息的 var,这可能与预期相符。
    猜你喜欢
    • 2018-10-05
    • 2013-05-05
    • 2010-09-18
    • 2018-08-01
    • 2012-01-03
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    相关资源
    最近更新 更多