如何在与 C++ 代码不同的终端中打开程序? [英] How do i open a program in a separate terminal from c++ code?

查看:25
本文介绍了如何在与 C++ 代码不同的终端中打开程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to do following tasks programmatically.

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

这是我的代码

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

但它在运行时出现以下错误.

But It gives following error on runtime.

sh: 0: Illegal option -

推荐答案

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

Beside the fact that there might be more elegant solutions than invoking a terminal via C++ to execute a programm you could go with one of these:

std::string

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

The most obvious solution is to use std::string which provides the overloaded operator + to concat strings.

#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 字符串,你可以使用这样的东西.请注意,我不推荐这样做.

If you want to use C strings you can use something like this. Note that I do not recommend this.

#include <cstring>

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

请注意,第二个版本需要仔细查看为 args 分配的内存.请参阅 strcat() 了解更多信息.

Please note, that the second version needs a closer look at the allocated memory for args. See strcat() for further information.

这篇关于如何在与 C++ 代码不同的终端中打开程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆