如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:

prog [-abc] [input [output]]

是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?


相关:

在unicode c++应用程序中解析命令行参数


当前回答

如果你可以使用boost库,我推荐boost::program_options。

在STL和常规的c++ /C运行时库中都没有特定的东西。

其他回答

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。

AnyOption是一个c++类,用于轻松解析复杂的命令行选项。它还以选项值对格式解析来自rsourcefile的选项。

AnyOption实现了传统的POSIX风格的字符选项(-n)以及较新的GNU风格的长选项(——name)。或者您可以通过要求忽略POSIX样式选项来使用更简单的长选项版本(-name)。

GNU C库中有这些工具,其中包括GetOpt。

如果你正在使用Qt并且喜欢GetOpt接口,那么froglogic已经在这里发布了一个不错的接口。

提振。Program_options

TCLAP是一个非常好的轻量级设计,易于使用: http://tclap.sourceforge.net/