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

如何用yaml-cpp生成指定格式的多行YAML文件?

Problem with yaml-cpp: Preserving Pipe Symbol and Multiline Format for hexa_frame

I'm trying to generate a YAML file with multiline content using the yaml-cpp library in C++. Here's my current code snippet:

YAML::Emitter out; 
out << YAML::BeginMap; 
out << YAML::Key << "name" << YAML::Value << "PKS2023/24" 
    << YAML::Key << "pcap_name" << YAML::Value << "abcd.pcap"; 
out << YAML::Key << "packets" << YAML::Value;

When I attempt to add a new mapping inside the value of hexa_frame, the output loses the pipe (|) symbol and introduces unwanted line breaks. How can I fix this to get the desired multiline YAML format?


Solution

To preserve the pipe symbol and maintain the multiline block scalar format for hexa_frame in yaml-cpp, you need to explicitly set the scalar style to Literal when emitting the content. Here's how to adjust your code:

  • Start the packets sequence: Since packets is likely a list of packet objects, open a sequence first:

    out << YAML::BeginSeq; // Start packets sequence
    
  • Define each packet with hexa_frame as a literal scalar: For each packet, create a map, and use YAML::Literal to enforce the pipe-style multiline format for hexa_frame:

    out << YAML::BeginMap; // Start individual packet map
    out << YAML::Key << "hexa_frame" << YAML::Value << YAML::Literal << R"(
    

00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
)";
// Add other packet fields (e.g., timestamp)
out << YAML::Key << "timestamp" << YAML::Value << "1234567890";
out << YAML::EndMap; // End packet map

- **Close the sequence and top-level map**:
```cpp
out << YAML::EndSeq; // End packets sequence
out << YAML::EndMap; // End top-level map

Key Notes

  • YAML::Literal tells yaml-cpp to emit the scalar as a literal block, which uses the | symbol and preserves line breaks exactly as written.
  • C++ raw string literals (R"(...)") avoid escaping newlines and special characters, simplifying multiline content input.

Example Output

The code will generate YAML like this:

name: PKS2023/24
pcap_name: abcd.pcap
packets:
  - hexa_frame: |
      00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
      00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
    timestamp: 1234567890

内容的提问来源于stack exchange,提问作者S. Zaprazny

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:08:18