【问题标题】:How do I create terminal commands in a c++ program?如何在 C++ 程序中创建终端命令?
【发布时间】:2012-12-11 05:37:50
【问题描述】:

我正在编写一个 c++ 程序,我希望人们能够从终端操作它。我唯一知道怎么做的是cin,虽然在接收到程序后可以采取行动,但我不会调用命令。 谢谢!!

【问题讨论】:

  • 哈??不明白你的问题,你尝试了什么?
  • 这几乎是基础。添加调用其他程序和内置函数、变量扩展、引用和通配符的能力,你就有了一个 shell。而是解析和解释一些编程语言,并且您有一个 REPL(读取-执行-打印-循环)控制台。

标签: c++ shell terminal command


【解决方案1】:

试试

#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";
    }
}

【讨论】:

    【解决方案2】:

    在您的程序中,使用备用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)
    

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 2016-04-05
      • 2020-07-23
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2015-10-01
      相关资源
      最近更新 更多