【问题标题】:Passing Arguments Through system() in C++在 C++ 中通过 system() 传递参数
【发布时间】:2015-09-30 14:53:56
【问题描述】:

如何通过 c++ 中的 system() 命令传递命令行变量。 我试过使用:

string i;
i = system("./findName.sh");
i += argv[1];
cout << i;

但是当我运行它时,它会给出我在 shell 脚本中编写的参数数量错误的条件。

这是我使用“./findName brandonw”运行程序时收到的输出。这是我的可执行文件与我希望我的 shell 脚本运行的参数一起运行。

The arguments you put are:
brandonw
usage: findName.sh [only_one_argument]

【问题讨论】:

标签: c++ bash shell variables


【解决方案1】:

只需将其连接到命令字符串即可。

string command = "./findName.sh";
command = command + " "  + argv[1];
system(command.c_str());

【讨论】:

    【解决方案2】:

    只需重新排列您的代码:

    string i("./findName.sh ");
    i += argv[1];
    system(i.c_str());
    cout << i;
    

    另请注意,system 不返回 std::string,而是一个实现定义的 int 值。

    如果你需要处理./findName.sh的输出,你宁愿需要pipe()

    【讨论】:

      猜你喜欢
      • 2012-08-12
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2016-05-13
      • 2013-11-19
      相关资源
      最近更新 更多