2012-12-25 30 views
2

我在寫一個C++程序,我希望人們能夠從終端操作它。我知道如何做的唯一的事情就是cin,儘管收到程序後可以採取行動,但我不會打電話給一個命令。 謝謝!如何在C++程序中創建終端命令?

+1

?不要問你的問題,你嘗試了什麼? –

+1

這幾乎是基礎。添加調用其他程序和內置函數,可變擴展,引用和通配符的能力,並且你有一個shell。相反,解析和解釋一些編程語言,你有一個REPL(讀執行打印循環)控制檯。 –

回答

3

嘗試

#include <iostream> 
int main(int argc, char* argv[]) 
{ 
    std::cout << "Command: " << argv[0] << "\n"; 
    for(int loop = 1;loop < argc; ++loop) 
    { 
     std::cout << "Arg: " << loop << ": " << argv[loop] << "\n"; 
    } 
} 
0

在程序中,使用備用int main簽名,它接受命令行參數。

int main(int argc, char* argv[]); 
// argc = number of command line arguments passed in 
// argv = array of strings containing the command line arguments 
// Note: the executable name is argv[0], and is also "counted" towards the argc count 

我也建議把在操作系統中的搜索路徑的可執行文件的位置,這樣就可以從任何地方調用它,而不必輸入完整的路徑。例如,如果你的可執行文件的名稱是foo,以及位於/home/me(在Linux上),然後使用下面的命令(KSH/bash shell中):

export PATH=$PATH:/home/me` 

在Windows上,你需要你的路徑追加到環境變量%PATH%

然後從任何地方撥打foo程序,與通常的:

foo bar qux 
(`bar` and `qux` are the command line arguments for foo) 
醫管局