使用 boost.program_options 解析命令行参数 - C++

Luk*_*ley 3 c++ boost

我正在尝试使用 boost 解析命令行参数。这是我的代码(我只包括我需要帮助的部分):

#include <iostream>
#include <iterator>
#include <boost/program_options.hpp>

using std::cerr;
using std::cout;
using std::endl;
namespace po = boost::program_options;

try {

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("compression", po::value<double>(), "set compression level");

    po::variables_map vm;
    po::store(po::parse_command_line(ac, av, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        cout << desc << "\n";
        return 0;
      }

    if (vm.count("compression")) {
        cout << "Compression level was set to "
             << vm["compression"].as<double>() << ".\n";
      } else {
            cout << "Compression level was not set.\n";
            }
      }
    catch(exception& e) {
        cerr << "error: " << e.what() << "\n";
        return 1;
    }
    catch(...) {
        cerr << "Exception of unknown type!\n";
    }
Run Code Online (Sandbox Code Playgroud)

我的主要功能设置为:

main(int argc, char const *argv[])
Run Code Online (Sandbox Code Playgroud)

但是,我关注的代码https://github.com/boostorg/program_options/blob/develop/example/first.cpp包含以下参数:

int main(int ac, char* av[])
Run Code Online (Sandbox Code Playgroud)

当我comile它时,它会吐出这个,我完全迷失了:

终端返回

sys*_*pro 8

您还忘记包含异常 - 这是您的代码工作..

#include <iostream>
#include <iterator>
#include <boost/program_options.hpp>
#include <exception>

using std::cerr;
using std::cout;
using std::endl;
using std::exception;
namespace po = boost::program_options;

int main(int ac, char** av){

try {

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("compression", po::value<double>(), "set compression level");

    po::variables_map vm;
    po::store(po::parse_command_line(ac, av, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        cout << desc << "\n";
        return 0;
      }

    if (vm.count("compression")) {
        cout << "Compression level was set to "
             << vm["compression"].as<double>() << ".\n";
      } else {
            cout << "Compression level was not set.\n";
            }
      }
    catch(exception& e) {
        cerr << "error: " << e.what() << "\n";
        return 1;
    }
    catch(...) {
        cerr << "Exception of unknown type!\n";
    return 1;
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译这个

g++ -std=c++11 cmd.cpp -l boost_program_options
Run Code Online (Sandbox Code Playgroud)

你应该没事

实际上,如果您愿意,您可以省略“std=c++11”。我都试过了,没问题