2011-05-04 60 views
14

我似乎无法从配置文件多命令读取像我可以从命令行读取选项。什么是配置文件的语法?boost :: program_options配置文件选项与多个标记

这是如何被添加的选项说明:

//parser.cpp 
- - - 
po::options_description* generic; 
generic=new po::options_description("Generic options"); 
generic->add_options() 
("coordinate",po::value<std::vector<double> >()->multitoken(),"Coordinates (x,y)"); 

后我解析命令和配置档案。

在命令行'--coordinate 1 2'工作。然而,当我尝试在配置文件中:

coordinate = 1,2 

coordinate= 1 2 

失败给人一种invalid_option_value例外。那么在多重选项选项的情况下,配置文件的语法究竟是什么?

+1

你不需要在这里使用'new'被暗示。如果你这样做,你会冒内存泄漏的风险。 – 2011-05-04 14:26:20

回答

6

您可以通过编写自定义验证器来实现您所寻求的行为。这种自定义的验证接受:

./progname --coordinate 1 2 
./progname --coordinate "1 2" 
#In config file: 
coordinate= 1 2 

下面是代码:

struct coordinate { 
    double x,y; 
}; 

void validate(boost::any& v, 
    const vector<string>& values, 
    coordinate*, int) { 
    coordinate c; 
    vector<double> dvalues; 
    for(vector<string>::const_iterator it = values.begin(); 
    it != values.end(); 
    ++it) { 
    stringstream ss(*it); 
    copy(istream_iterator<double>(ss), istream_iterator<double>(), 
     back_inserter(dvalues)); 
    if(!ss.eof()) { 
     throw po::validation_error("Invalid coordinate specification"); 
    } 
    } 
    if(dvalues.size() != 2) { 
    throw po::validation_error("Invalid coordinate specification"); 
    } 
    c.x = dvalues[0]; 
    c.y = dvalues[1]; 
    v = c; 
} 
... 
    po::options_description config("Configuration"); 
    config.add_options() 
     ("coordinate",po::value<coordinate>()->multitoken(),"Coordinates (x,y)") 
     ; 

参考文献:

8

在您的配置文件中,将矢量的每个元素放在不同的行上。

coordinate=1 
coordinate=2 
+0

完美地工作 – kshahar 2012-05-03 14:11:41

0

在发现自己面临着类似的问题,我把上面的代码从罗布的回答(从2011年5月4日),但后来换了几件事情,由于在升压架构和C的变化++ 11。我只引用了我改变的部分(或者会改变)。不在验证函数内的其余部分保持不变。出于符合性的原因,我添加了必要的std ::前缀。

namespace po = boost::program_options; 

void validate(boost::any& v, 
    const std::vector<std::string>& values, 
    coordinate*, int) { 
    coordinate c; 
    std::vector<double> dvalues; 
    for(const auto& val : values) { 
    std::stringstream ss(val); 
    std::copy(std::istream_iterator<double>(ss), std::istream_iterator<double>(), 
     std::back_inserter(dvalues)); 
    if(!ss.eof()) { 
     throw po::invalid_option_value("Invalid coordinate specification"); 
    } 
    } 
    if(dvalues.size() != 2) { 
    throw po::invalid_option_value("Invalid coordinate specification"); 
    } 
    c.x = dvalues[0]; 
    c.y = dvalues[1]; 
    v = c; 
} 

蒲:: VALIDATION_ERROR到PO :: invalid_option_value的转变https://stackoverflow.com/a/12186109/4579106

相关问题