【问题标题】:How can I invoke the System() function inside a function in my c++ code?如何在我的 c++ 代码中的函数内调用 System() 函数?
【发布时间】:2018-03-18 09:00:41
【问题描述】:

我来调用 then 函数一切顺利

int status = system("./my_exe_file input output");

但是当我想在函数中调用它时,我在处理文件时遇到了一点问题:

void call(std::string f){
  FILE *in = fopen (in, "r");  
  int status = system("./my_exe_file f output");   
}

谁能告诉我该怎么做?

【问题讨论】:

  • 你需要将你的字符串连接在一起......
  • 怎么办?有什么问题?有什么问题?
  • @EJP:OP 想要在传递给system 的字符串中插入f
  • FILE *in = fopen (in, "r"); 应该做什么?这种方式毫无意义。正确的in不应该是f吗?
  • @MatsPetersson 我在这里只能看到“我在处理文件时遇到了一点问题”。这不是问题描述。代码甚至无法编译。

标签: c++ file system


【解决方案1】:

不可能像你那样通过简单地将变量名写在字符串文字中来连接字符串。

要连接 2 个或多个字符串,您可以使用 std::string+/+= 运算符。

std::string command = std::string("./my_exe_file ") + f + " output";
system( command.c_str() );

请注意,第一个文字 "./my_exe_file " 必须封装在字符串中,因为您可以将字符串文字添加到字符串,将字符串添加到字符串,但不能将字符串添加到字符串文字。

还要注意,在第二行中,system() 调用需要一个 C 字符串 (char*)。 std::string::c_str() 为您提供 std::string 的 C 字符串表示形式。

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2012-12-04
    • 2017-04-22
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多