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

时间:2017-08-02 17:03:46

标签: 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";
    }

我的主要功能设置为:

main(int argc, char const *argv[])

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

int main(int ac, char* av[])

当我加入它时,它吐出这个并且我完全迷失了:

Terminal return

1 个答案:

答案 0 :(得分:2)

你也忘了包含异常 - 这是你的代码工作..

#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;
}

编译
g++ -std=c++11 cmd.cpp -l boost_program_options

你应该没事。

实际上你可以省去&#34; std = c ++ 11&#34;如果你想。我已经尝试了它和它的确定