BOOST程序选项命令行的格式是什么?

What is the format of BOOST program options command lines?

本文关键字:格式 是什么 命令行 程序 选项 BOOST      更新时间:2023-10-16

我有两个开关,' I '和'p'分别代表IPAddress和Port。

命令行格式是什么?

I have try:

app -i192.168.1.1 -p12345
app -i 192.168.1.1 -p 12345
app -i=192.168.1.1 -p=12345
app -i='192.168.1.1' -p='12345'
app --IPAddress 192.168.1.1 --Port12345

我的应用程序在IPAddress上有问题,并且使用DDD进行故障排除是不透漏的,因为我得到了vm。

此外,应用程序作为守护进程运行,因此我的IP地址和端口的cout语句将被遗忘,并且由于输出值不是const char*而阻碍了打印到syslog。

我打算在其他事情上也使用程序选项,但是我对这个有点不知所措。

po::options_description config("Configuration");
        config.add_options()
            ("IPAddress,i","IP Address")
            ("Port,p","Port")
             ;
po::variables_map vm;
        po::store(po::parse_command_line(ac, av, config),
                       vm);
        po::notify(vm);
//...and this is how the values are used
int retval = getaddrinfo((vm["IPAddress"].as< string >()).c_str(),(vm["Port"].as<string>()).c_str(), &hint, &list);

这是一个完整的程序…在'Values'之后不会打印任何内容到控制台:

#include <sstream>
#include <algorithm>
#include <stdlib.h>
#include <iterator>
#include <string>
//Using boost program options to read command line and config file data
#include <boost/program_options.hpp>
using namespace std;
using namespace boost;
namespace po = boost::program_options;
int main (int argc, char *argv[])
{
    po::options_description config("Configuration");
    config.add_options()
                ("IPAddress,i","IP Address")
                ("Port,p","Port")
                 ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, config),vm);
    po::notify(vm);
    cout << "Valuesn";
    cout << (vm["IPAddress"].as< string >()).c_str();
    cout << " " << (vm["Port"].as<string>()).c_str();
    return 0;
}

输入的值是不可打印的吗?


这里是gdb的输出,似乎是被强制转换的问题:

28              string address = (vm["IPAddress"].as< string >()).c_str();
(gdb) n
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_any_cast> >'
  what():  boost::bad_any_cast: failed conversion using boost::any_cast
Program received signal SIGABRT, Aborted.
0x0000003afd835935 in raise () from /lib64/libc.so.6

BOOST程序选项支持Unix系统中常见的命令行风格。因此,这两个应该工作(他们正在为我工作)

app -i 192.168.1.1 -p 12345
app --IPAddress=192.168.1.1 --Port=12345

备注:

    基本教程的文档在boost.org(可能你已经知道了)写一个独立的单元测试当然是一个很好的建议;boost还为c++ 提供了一个易于使用的测试框架