如何将YAML节点中的序列作为字符串返回?

问题描述 投票:0回答:1

我正在尝试使用yaml-cpp在C ++中解析对话树(YAML)。这是一个样本YAML:

dialogue_block:
  character_name:
    - Hello
    - How are you?
    - :main
main:
  - 1: ["I'm fine, thank you", :response1]
  - 2: ["Not very well", :response2]
  - 3: ["I don't want to talk", :exit]

我对C ++和Yaml比较陌生,所以如果有更容易/更直观的方式,请指出我正确的方向。我的想法是将每个块存储为对话节点。在上面的例子中,我希望能够调用dialogue_block,并提取character_name来识别角色说话,打印所有序列到:main,它将切换到main节点,为玩家提供3种选择。我目前停留在第1步 - 解析yaml文件...

以下作品......

YAML::Node dialogue = YAML::LoadFile("dialogue.yaml");
if(dialogue["dialogue_block"]){
  std::cout << dialogue["dialogue_block"]["character_name"][0].as<std::string>() << "\n";
}

它打印“你好”。但是,我对接下来的步骤感到困惑:如何在不将字符串硬编码到我的代码中的情况下检索“character_name”?有没有办法打印所有字符串,但不包括“:main”?然后将“main”作为下一个节点?

第一次在stackoverflow上发布,所以如果需要更多信息,请告诉我!谢谢。

编辑:这是我正在使用的更新代码:

// read in file
YAML::Node dialogue = YAML::LoadFile("dialogue.yaml");

// Extract names of each block
std::vector<std::string> dialogueBlocks;
for (const auto& kv : dialogue) {
    dialogueBlocks.push_back(kv.first.as<std::string>());
} // will return "dialogue_block" and "main" 

std::string character;

// if first_encounter exists, always start at that block
if(dialogue["first_encounter"]){
    for(YAML::iterator it = dialogue["first_encounter"].begin(); it != dialogue["first_encounter"].end(); ++it){
        character = it->first.as<std::string>();
        std::cout << "\nCharacter: " << character << "\n";
        for (YAML::iterator it=dialogue["first_encounter"][character].begin();it!=dialogue["first_encounter"][character].end(); ++it) {
        std::cout << it->as<std::string>() << "\n";
    }
    }

}

我可以成功地提取角色名称和对话,但有一些我正在努力的事情:1)它还打印“:main”,我希望它可以省略。我不知道当它到达以“:”开头的字符串时,或者如果有合适的内置函数可以使它终止。 2)将“:main”存储为下一个块,以便在调用时通过for循环。

c++ yaml yaml-cpp
1个回答
0
投票

您正在询问如何找到列表的“密钥名称”。你当然可以查看dialogue["dialogue_block"]下的所有按键,但是将character作为lines的单独字段会更加惯用yaml,就像这样

dialogue_block:
  character: Bob
  lines:
    - Hello
    - How are you?
    - :main

或者如果一个块是一个列表,

dialogue_block:
  - character: Bob
    lines:
      - Hello
      - How are you?
      - :main
  - character: Alice
    lines:
      - Blah
      - :main
© www.soinside.com 2019 - 2024. All rights reserved.