如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
当前回答
TCLAP是一个非常好的轻量级设计,易于使用: http://tclap.sourceforge.net/
其他回答
如果你可以使用boost库,我推荐boost::program_options。
在STL和常规的c++ /C运行时库中都没有特定的东西。
如果你只想自己处理命令行选项,最简单的方法是:
vector<string> args(argv + 1, argv + argc);
在main()的顶部。这将把所有命令行参数复制到std::strings的向量中。然后,您可以使用==轻松地比较字符串,而不是无休止的strcmp()调用。例如:
int main(int argc, char **argv) {
vector<string> args(argv + 1, argv + argc);
string infname, outfname;
// Loop over command-line args
// (Actually I usually use an ordinary integer loop variable and compare
// args[i] instead of *i -- don't tell anyone! ;)
for (auto i = args.begin(); i != args.end(); ++i) {
if (*i == "-h" || *i == "--help") {
cout << "Syntax: foomatic -i <infile> -o <outfile>" << endl;
return 0;
} else if (*i == "-i") {
infname = *++i;
} else if (*i == "-o") {
outfname = *++i;
}
}
}
[编辑:我意识到我正在复制argv[0],程序的名称,到args -已修复。]
GNU C库中有这些工具,其中包括GetOpt。
如果你正在使用Qt并且喜欢GetOpt接口,那么froglogic已经在这里发布了一个不错的接口。
您可以使用GNU GetOpt (LGPL)或各种c++端口之一,例如getoptpp (GPL)。
一个简单的例子使用GetOpt你想要的东西(prog [-ab] input)如下:
// C Libraries:
#include <string>
#include <iostream>
#include <unistd.h>
// Namespaces:
using namespace std;
int main(int argc, char** argv) {
int opt;
string input = "";
bool flagA = false;
bool flagB = false;
// Retrieve the (non-option) argument:
if ( (argc <= 1) || (argv[argc-1] == NULL) || (argv[argc-1][0] == '-') ) { // there is NO input...
cerr << "No argument provided!" << endl;
//return 1;
}
else { // there is an input...
input = argv[argc-1];
}
// Debug:
cout << "input = " << input << endl;
// 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;
}
如果你不想使用boost,我推荐这个小助手类。