如何在C++中修改TOML文件(TOML++)

3

我正在使用 toml++。如何在 C++ 中使用 toml++ 修改 TOML 文件的特定值。

json ConfigService::getAllData(std::string filePath)
{
    try
    {
        auto _data_table = toml::parse_file(filePath);
        _data_table["config_paths"]["DIAAI_core"] = "diaaiSetting.toml";  # this is not working
        cout << _data_table << endl;
    }
    catch (const exception err)
    {
        std::cerr << "Parsing failed:\n"
                  << err.what() << "\n";
        std::runtime_error(err.what());
    }
}

追踪回溯

error: no match for ‘operator=’ (operand types are ‘toml::v3::node_view<toml::v3::node>’ and ‘int’)
   51 |         _data_table["config_paths"] = 1;
1个回答

2

最近几天,我也遇到了这个问题,并尝试了许多使用toml++设置值的方法。我想到的方法可能只是一个临时解决方案,但它工作得相当不错。

#include <iostream>
#include <toml++/toml.hpp>
using namespace std::string_view_literals;

int main() {
    static constexpr auto source = R"(
        [config_paths]
        DIAAI_core = [""]
    )"sv;
    toml::table _data_table      = toml::parse(source);

    if (toml::array* arr = _data_table["config_paths"]["DIAAI_core"].as_array()) {
        arr->for_each([](auto&& el) {
            if constexpr (toml::is_string<decltype(el)>)
                if(el == "")
                    el = "diaaiSetting.toml"sv;
        });
    }
    std::cout << _data_table << std::endl; 
    return 0;
}

output: 
[config_paths]
DIAAI_core = [ 'diaaiSetting.toml' ]

这个值本身不是一个字符串,而是一个只包含一个值的字符串数组,因此反序列化应该相当容易。

您可以轻松地在toml11中与值进行交互,如果这不适合您,您可能需要查看它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接