0

如何在命令行中的某个字符串之后捕获参数?

./executable.out -apps path_to_out

在上面的代码中,我想将 path_to_out 存储在一个字符串变量中。这样做的有效方法是什么?

4

4 回答 4

4

It kind of depends what kind of options you want. If you are willing to have only single-letter options, you can use the C library function getopt to parse the command line. If you would like long options (e.g., --apps), you can use getopt_long, but this is a GNU extension that will not port well. If you want really, really fancy option parsing, you can use something like GLib.

Of course, you can just roll your own, iterating over the arguments from 1 to argc and, when you encounter -apps, check that i+1 < argc and grab the next argument.

于 2012-08-23T05:25:09.017 回答
1

argv[argc-1] already has the value for you if your path is the last argument in the command line.

if your main is like :

int main(int argc,char **argv)

all the command line arguments are in char **argv. in your case: argv[2] is path_to_out. if you want to copy it in a string,you can anyhow do this below thing:

string path(argv[2]);
于 2012-08-23T05:22:41.547 回答
0

看来,通过询问“在命令行上的某个字符串之后”,您指的是命令行参数-apps以破折号开头的事实,这使其成为“选项”。

这样做的首选方法是使用预定义的库来处理选项,例如GNU 系统上的getopt

于 2012-08-23T05:26:43.480 回答
0

当您以这种方式运行参数存储时..

示例:---> ./executable.out -apps path_to_out

argv[0] will be "./executable.out"
argv[1] will be "-apps"
and argv[2] will be "path_to_out".
于 2012-08-23T05:26:51.747 回答