2

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

4

2 回答 2

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";
    }
}
于 2012-12-25T03:27:36.833 回答
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)
于 2012-12-25T03:32:28.380 回答