【问题标题】:How to embed commandline arguments in a execution command?如何在执行命令中嵌入命令行参数?
【发布时间】:2015-06-15 14:50:34
【问题描述】:

我需要将我的 C++ 代码的命令行参数作为我的 python 脚本的命令行参数传递。

我的代码如下:

int main(int argc,char * argv[]) {
FILE *in;
char buff[512];

cout<<argv[1];

string str = "python comparescript.py "+argv[1]+" "+argv[2]+" "+argv[3];

if(!(in = popen(str, "r"))){
    cout<<"Image Comparison made successful";
}
cout<<"Image Comparison made successful";

它显示如下错误:

错误:“const char [25]”和“char*”类型的无效操作数转换为二进制“operator+”

如何在 python 执行命令中附加我的命令行参数?

【问题讨论】:

  • const char[]std::string 之间存在差异。该字符串是一个 C++ 类,而 char[] 是一个基元数组。我会研究 C++ 字符串以了解更多如何创建和操作它们。 cplusplus.com/reference/string/string

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


【解决方案1】:

为了能够使用+ 运算符连接字符串,其中至少一个必须是std::string 对象。

最简单的解决方案?做吧

string str = string("python comparescript.py ")+argv[1]+" "+argv[2]+" "+argv[3];

【讨论】:

  • 谢谢!添加 strdup() 并在此解决问题后将它们转换为 c 字符串!
  • @KaushikRamachandran 什么,strdup?转换为 C 字符串?为什么?第一个可能导致内存泄漏(记住strdup 分配内存),第二个不需要。
猜你喜欢
  • 1970-01-01
  • 2011-10-31
  • 2012-11-06
  • 1970-01-01
  • 2013-01-13
  • 2020-09-15
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多