You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

toml11库序列化文件路径字符串的异常问题求助

解决toml11序列化Windows路径为多行字符串的问题

问题场景

开发桌面应用时使用toml11库读写TOML配置文件,将用户选择的目录路径持久化到文件时,路径被序列化为多行带转义的多行字符串格式,而非期望的单行标准字符串格式。其他长字符串序列化正常,仅路径出现此问题,解析路径无异常。

复现代码

#include <iostream>
#include <toml.hpp>
#include <string>
#include <Windows.h>
#include <locale>
#include <codecvt>

int main()
{
    TCHAR path[MAX_PATH];
    GetModuleFileName(NULL, path, ARRAYSIZE(path));
    std::wstring exePath(path);
    std::wcout << exePath << " \n";

    using convert_type = std::codecvt_utf8<TCHAR>;
    std::wstring_convert<convert_type, TCHAR> converter;
    std::string sExePath = converter.to_bytes(exePath);

    auto parsedData = toml::parse("sample.toml");
    auto& parsedExePath = toml::find<std::string>(parsedData, "exePath");
    std::cout << parsedExePath << " \n";

    const toml::value data{ { {"exePath", sExePath} } };

    const std::string configString = toml::format(data);

    std::cout << configString << " \n";

    return 0;
}

实际输出

C:\Users\segmentation_fault\source\repos\Toml11FilePathsMre\x64\Debug\Toml11FilePathsMre.exe
C:\Development\cpp
exePath = """
C:\\Users\\segmentation_fault\\source\\repos\\Toml11FilePathsMre\\x64\\Deb\
ug\\Toml11FilePathsMre.exe\
"""


C:\Users\segmentation_fault\source\repos\Toml11FilePathsMre\x64\Debug\Toml11FilePathsMre.exe (process 13700) exited with code 0.

期望输出

exePath = "C:\\Users\\segmentation_fault\\source\\repos\\Toml11FilePathsMre\\x64\\Debug\\Toml11FilePathsMre.exe"

解决方案

原因分析

toml11库默认会对较长的字符串或包含转义序列的字符串自动启用多行字符串格式,同时为了可读性拆分长行,导致Windows路径被处理成多行带延续符的格式。

修改方法

调用toml::format时传入toml::format_flags::no_multiline_strings标志,强制所有字符串以单行标准格式输出。

修改后的关键代码片段:

// 替换原format调用
const std::string configString = toml::format(data, toml::format_flags::no_multiline_strings);

修改后,路径会被序列化为期望的单行标准字符串格式,同时完全兼容TOML的解析规则。

内容的提问来源于stack exchange,提问作者segmentation_fault

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:28:19