繁体   English   中英

如何在与C ++代码不同的终端中打开程序?

[英]How do i open a program in a separate terminal from c++ code?

我想以编程方式执行以下任务。

  1. 在C ++中,打开一个终端(system(“ gnome-terminal”);)
  2. 在C ++中,运行某个位置的程序(./myprogram)

这是我的代码

strcpy(args, "gnome-terminal");
strcpy(args, "-e 'sh ./spout");
strcat(args, "' ");
system(args);

但是它在运行时给出以下错误。

sh: 0: Illegal option -

除了以下事实之外,可能还有比通过C ++调用终端来执行程序更优雅的解决方案,您可以选择以下一种:

的std :: string

最明显的解决方案是使用std::string ,它提供重载的运算符+来连接字符串。

#include <string>

std::string args = "gnome-terminal ";
args += "-e 'sh ./spout";
args += "' ";

的std :: stringstream的

std::stringstream是另一种选择:

#include <sstream>
#include <string>

std::stringstream ss;
ss << "gnome-terminal "; 
ss << "-e 'sh ./spout";
ss << "' ";
std::string args = ss.str();

strcat的()

如果要使用C字符串,可以使用类似这样的东西。 请注意,我不建议这样做。

#include <cstring>

strcpy(args, "gnome-terminal");
strcat(args, "-e 'sh ./spout");
strcat(args,  "' ");

请注意,第二个版本需要仔细查看为args分配的内存。 有关更多信息,请参见strcat()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM