如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
当前回答
如果这是linux/unix,那么使用的标准是gnu getopt
http://www.gnu.org/s/libc/manual/html_node/Getopt.html
其他回答
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i],"-i")==0) {
filename = argv[i+1];
printf("filename: %s",filename);
} else if (strcmp(argv[i],"-c")==0) {
convergence = atoi(argv[i + 1]);
printf("\nconvergence: %d",convergence);
} else if (strcmp(argv[i],"-a")==0) {
accuracy = atoi(argv[i + 1]);
printf("\naccuracy:%d",accuracy);
} else if (strcmp(argv[i],"-t")==0) {
targetBitRate = atof(argv[i + 1]);
printf("\ntargetBitRate:%f",targetBitRate);
} else if (strcmp(argv[i],"-f")==0) {
frameRate = atoi(argv[i + 1]);
printf("\nframeRate:%d",frameRate);
}
}
提振。Program_options应该可以做到这一点
我建议你去图书馆。有经典而古老的getopt,我相信还有其他的。
如果你可以使用boost库,我推荐boost::program_options。
在STL和常规的c++ /C运行时库中都没有特定的东西。
如果可以的话,我还建议查看一下我编写的选项解析库:drop。
它是一个C库(如果需要,还带有c++包装器)。 它是轻量级的。 它是可扩展的(自定义参数类型可以很容易地添加,并且与内置参数类型具有相同的基础)。 它应该是非常可移植的(它是用标准C编写的),没有依赖关系(除了C标准库)。 它有一个非常无限制的许可证(zlib/libpng)。
它提供了许多其他功能没有的一个功能是覆盖先前选项的能力。例如,如果你有一个shell别名:
alias bar="foo --flag1 --flag2 --flag3"
你想要使用bar但禁用了——flag1,它允许你做:
bar --flag1=0