我正在编写一个C 程序,我希望人们能够从终端操作它。我知道该怎么做的唯一一件事是cin
,尽管收到程序可以采取行动,但我不会呼叫命令。谢谢!
尝试
#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";
}
}
在您的程序中,使用替代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)