如何用yaml-cpp生成指定格式的多行YAML文件?
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
packetssequence: Sincepacketsis likely a list of packet objects, open a sequence first:out << YAML::BeginSeq; // Start packets sequenceDefine each packet with
hexa_frameas a literal scalar: For each packet, create a map, and useYAML::Literalto enforce the pipe-style multiline format forhexa_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::Literaltells 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

