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

编程入门 行业动态 更新时间:2024-10-26 06:26:27
本文介绍了如何在与 C++ 代码不同的终端中打开程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

I want to do following tasks programmatically.

在 C++ 中,打开一个终端 (system("gnome-terminal");) 在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 07:26:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1186760.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:终端   在与   代码   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!