2017-04-11 55 views
0

我想以編程方式執行以下任務。如何從C++代碼打開一個單獨的終端程序?

  1. 在C++中,打開一個終端(系統( 「侏儒端」);)
  2. 在C++中, 運行

這裏是位於一些地方(./myprogram)中的程序我的代碼

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

但它給運行時帶來以下錯誤。

sh: 0: Illegal option - 
+2

第二個'strcpy'會覆蓋第一個'strcpy'。你爲什麼不使用'std :: string?' – Quentin

回答

0

旁邊的事實,有可能更優雅的解決方案不是通過C++執行PROGRAMM你可以用其中的一個去調用終端:

的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()