【问题标题】:Get a string from the command line when using boost program_options使用 boost program_options 时从命令行获取字符串
【发布时间】:2012-10-30 17:34:12
【问题描述】:

我正在使用 boost program_options 库来处理命令行和配置文件数据,但我不清楚如何从处理后的数据中获取所需的字符串。

如何将 program_options 命令行参数转换为 getaddrinfo 函数的正确格式。

//First, the options are declared

po::options_description config("Configuration");
    config.add_options()
        ("IPAddress", po::value< vector<string> >(),"127.0.0.1")
        ("Port", po::value< vector<string> >(),"5000")
         ;
//...

// Attach the config descriptions to the command line and/or config file

    po::options_description cmdline_options;
    cmdline_options.add(config).add(hidden);

    po::options_description config_file_options;
            config_file_options.add(hidden);

    po::options_description visible("Allowed options");
            visible.add(config);

    po::positional_options_description p;
            p.add("input-file", -1);

    po::variables_map vm;
    store(po::command_line_parser(ac, av).
          options(cmdline_options).positional(p).run(), vm);
    notify(vm);

// Use the command line options for IPAddress and Port
// TODO: Load the config file's address and port information
int retval = getaddrinfo(vm["IPAdress"].as< string >(),vm["Port"].as<string>(),    &hint, &list);
// This doesn't work and neither does this
//  int retval = getaddrinfo(vm["IPAdress"].as< vector<string> >(),vm["Port"].as<vector <string> >(),    &hint, &list);

// getaddressinfo

netdb 中 getaddrinfo 的原型是:

extern int getaddrinfo (__const char *__restrict __name,
        __const char *__restrict __service,
        __const struct addrinfo *__restrict __req,
        struct addrinfo **__restrict __pai);

这里是 boost program_options API 的链接:

http://www.boost.org/doc/libs/1_37_0/doc/html/program_options.html

【问题讨论】:

    标签: linux boost boost-program-options


    【解决方案1】:

    如果所需的参数应该具有char * 类型并且您尝试提供string,编译器会告诉您出了什么问题。阅读该错误消息并尝试理解它。

    要从string 获取char *,请使用c_str() 方法。

    【讨论】:

    • 谢谢。我不知道在哪里应用 c_str() 函数。我试图像这样将它固定在最后:“IPAdress”].as().c_str(),而我真正需要做的是 (“IPAdress”].as())。 c_str()
    • @bentaisan 不客气。记住,编译器是你的朋友。 :)
    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 2011-05-04
    • 2019-03-21
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    相关资源
    最近更新 更多