首页 > 解决方案 > 如何实现文件读取和创建到结构中

问题描述

不知道如何实现读取数据并放入结构体

有一个 config.txt 文件,它存储数据,如

someBigText=ASDSDdasdsa (can be more +1000 simbol)
isOkay=true
myAge=24
struct Config {
    std::string Name;
    std::string StringValue;
};

标签: c++

解决方案


假设您的配置分为以下部分:

[myImportantSection] 
someBigText = "foo tha can be more +1000 simbols" 
isOkay = true 
myAge = 24

并假设您正在使用 boost:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>



boost::property_tree::ptree myPtree;
boost::property_tree::ini_parser::read_ini("config.txt", myPtree);
auto text{myPtree.get<std::string>("myImportantSection.someBigText")};
auto isOk{myPtree.get<bool>("myImportantSection.isOkay")};
auto age{myPtree.get<int>("myImportantSection.myAge")};

struct Config
{
    std::string text{};
    bool ok{false};
    int age{0};
};

Config myConfig;

myConfig.text = text;
myConfig.ok = isOk;
myConfig.age = age;

推荐阅读