如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:
prog [-abc] [input [output]]
是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?
相关:
在unicode c++应用程序中解析命令行参数
当前回答
Qt 5.2提供了一个命令行解析器API。
小例子:
#include <QCoreApplication>
#include <QCommandLineParser>
#include <QDebug>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
app.setApplicationName("ToolX");
app.setApplicationVersion("1.2");
QCommandLineParser parser;
parser.setApplicationDescription("Tool for doing X.");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("infile",
QCoreApplication::translate("main", "Input file."));
QCommandLineOption verbose_opt("+",
QCoreApplication::translate("main", "be verbose"));
parser.addOption(verbose_opt);
QCommandLineOption out_opt(QStringList() << "o" << "output",
QCoreApplication::translate("main", "Output file."),
QCoreApplication::translate("main", "filename"), // value name
QCoreApplication::translate("main", "out") // default value
);
parser.addOption(out_opt);
// exits on error
parser.process(app);
const QStringList args = parser.positionalArguments();
qDebug() << "Input files: " << args
<< ", verbose: " << parser.isSet(verbose_opt)
<< ", output: " << parser.value(out_opt)
<< '\n';
return 0;
}
示例输出
自动生成的帮助界面:
$ ./qtopt -h Usage: ./qtopt [options] infile Tool for doing X. Options: -h, --help Displays this help. -v, --version Displays version information. -+ be verbose -o, --output Output file. Arguments: infile Input file.
自动生成版本输出:
$ ./qtopt -v ToolX 1.2
一些真实的电话:
$ ./qtopt b1 -+ -o tmp blah.foo Input files: ("b1", "blah.foo") , verbose: true , output: "tmp" $ ./qtopt Input files: () , verbose: false , output: "out"
解析错误:
$ ./qtopt --hlp Unknown option 'hlp'. $ echo $? 1
结论
如果您的程序已经使用了Qt(>= 5.2)库,那么它的命令行解析API足以方便地完成工作。
请注意,内置Qt选项在选项解析器运行之前会被QApplication使用。
其他回答
你可能想要使用一个外部库。有很多选择。
Boost有一个非常丰富的功能(像往常一样)库Boost程序选项。
过去几年我个人最喜欢的是TCLAP——纯粹的模板化,因此没有库或链接,自动生成“——帮助”和其他好东西。请参阅文档中最简单的示例。
Argstream与boost非常相似。Program_option:它允许将变量绑定到选项等。但是,它不处理存储在配置文件中的选项。
TCLAP是一个非常好的轻量级设计,易于使用: http://tclap.sourceforge.net/
我建议你去图书馆。有经典而古老的getopt,我相信还有其他的。
我喜欢C的getopt(),但是我老了。: -)