2012-06-16 5 views

Trả lời

10

Đối với tệp cấu hình tùy chọn chương trình tăng cường, nếu dòng không khai báo một phần, chẳng hạn như [settings], thì nó cần phải ở định dạng name=value. Ví dụ của bạn, hãy viết như sau:

[plugins] 
name = somePlugin 
name = HelloWorldPlugin 
name = AnotherPlugin 
[settings] 
type = hello world

Tùy chọn plugin bây giờ sẽ tương ứng với tùy chọn "plugins.name", tùy chọn cần phải là tùy chọn đa ngôn ngữ.

Dưới đây là một chương trình ví dụ mà đọc các thiết lập ở trên từ một tập tin settings.ini:

#include <boost/program_options.hpp> 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 

int main() 
{ 
    namespace po = boost::program_options; 

    typedef std::vector<std::string> plugin_names_t; 
    plugin_names_t plugin_names; 
    std::string settings_type; 

    // Setup options. 
    po::options_description desc("Options"); 
    desc.add_options() 
    ("plugins.name", po::value<plugin_names_t>(&plugin_names)->multitoken(), 
        "plugin names") 
    ("settings.type", po::value<std::string>(&settings_type), 
         "settings_type"); 

    // Load setting file. 
    po::variables_map vm; 
    std::ifstream settings_file("settings.ini" , std::ifstream::in); 
    po::store(po::parse_config_file(settings_file , desc), vm); 
    settings_file.close(); 
    po::notify(vm);  

    // Print settings. 
    typedef std::vector<std::string>::iterator iterator; 
    for (plugin_names_t::iterator iterator = plugin_names.begin(), 
             end = plugin_names.end(); 
     iterator < end; 
     ++iterator) 
    { 
    std::cout << "plugin.name: " << *iterator << std::endl; 
    } 
    std::cout << "settings.type: " << settings_type << std::endl; 

    return 0; 
} 

nào xuất ra như sau:

plugin.name: somePlugin 
plugin.name: HelloWorldPlugin 
plugin.name: AnotherPlugin 
settings.type: hello world
+0

Cảm ơn, vì vậy không có cách làm thế nào để làm điều đó mà không cần phải có "name =" trước tên plugin? – user1307957

+0

Nếu không có trình phân tích cú pháp khách hàng của riêng bạn, không. –

+0

Ok, không bao giờ. – user1307957