如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
当前回答
Argstream与boost非常相似。Program_option:它允许将变量绑定到选项等。但是,它不处理存储在配置文件中的选项。
其他回答
尝试Boost::Program Options。它允许您读取和解析命令行以及配置文件。
GNU顶。
一个使用GetOpt的简单示例:
// C/C++ Libraries:
#include <string>
#include <iostream>
#include <unistd.h>
// Namespaces:
using namespace std;
int main(int argc, char** argv) {
int opt;
bool flagA = false;
bool flagB = false;
// Shut GetOpt error messages down (return '?'):
opterr = 0;
// Retrieve the options:
while ( (opt = getopt(argc, argv, "ab")) != -1 ) { // for each option...
switch ( opt ) {
case 'a':
flagA = true;
break;
case 'b':
flagB = true;
break;
case '?': // unknown option...
cerr << "Unknown option: '" << char(optopt) << "'!" << endl;
break;
}
}
// Debug:
cout << "flagA = " << flagA << endl;
cout << "flagB = " << flagB << endl;
return 0;
}
如果有接受参数的选项,也可以使用optarg。
你可能想要使用一个外部库。有很多选择。
Boost有一个非常丰富的功能(像往常一样)库Boost程序选项。
过去几年我个人最喜欢的是TCLAP——纯粹的模板化,因此没有库或链接,自动生成“——帮助”和其他好东西。请参阅文档中最简单的示例。
如果可以的话,我还建议查看一下我编写的选项解析库:drop。
它是一个C库(如果需要,还带有c++包装器)。 它是轻量级的。 它是可扩展的(自定义参数类型可以很容易地添加,并且与内置参数类型具有相同的基础)。 它应该是非常可移植的(它是用标准C编写的),没有依赖关系(除了C标准库)。 它有一个非常无限制的许可证(zlib/libpng)。
它提供了许多其他功能没有的一个功能是覆盖先前选项的能力。例如,如果你有一个shell别名:
alias bar="foo --flag1 --flag2 --flag3"
你想要使用bar但禁用了——flag1,它允许你做:
bar --flag1=0
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);
}
}