镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Comment after literal string #800

Open

Description

@vokimon

By running this code:

#include <yaml-cpp/yaml.h>
#include <iostream>
#include <fstream>

int main() {
    {
        std::ofstream f("hola.yaml");
        YAML::Emitter emitter(f);
        emitter << YAML::Literal << "Hello\nworld" << YAML::Comment("Un comentario");
    }
    {
        std::ifstream f("hola.yaml");
        YAML::Node node = YAML::Load(f);
        std::cout << node.as<std::string>() << std::endl;
    }
    return 0;
}

The first part generates the following content:

|
  Hello
  world # A comment

When the second part reads it back, the comment is read as part of the literal. One of them, reading or writing is wrong. Specs says that no comments can be placed inside an scalar, since a literal is an scalar and it terminates with the indentation back, it sounds like the reading is right and the writing is wrong.

When a scalar is inserted in literal mode comments inserted next should be at the next line. and outside of the indentation. Like this:

|
  Hello
  world
# A comment

Activity

  1. vokimon commented on Jan 8, 2020

    @vokimon
    Author

    Work arround: inserting a Newline after the literal. Caution: this is parsed as having an endline at the end of the string ("Hello\nworld\n") instead of the inserted ("Hello\nworld"). It is better than having the comment included in the literal ("Hello\nworld # Un comentario") but stil write/read is not idempotent.

        {
            std::ofstream f("hola.yaml");
            YAML::Emitter emitter(f);
            emitter
                << YAML::Literal << "Hello\nworld"
                << YAML::Newline << YAML::Comment("Un comentario")
                ;
        }
  2. SGSSGene commented on Mar 19, 2026

    @SGSSGene
    Collaborator

    This is a bug, and on first sight hard to fix in yaml-cpp.
    But #1424 is fixing the handling of the trailing '\n', which will make your work around at least idempotent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions