Yaml-cpp似乎正在我的地图条目前插入一个问号。这是结果:
baryons:
nucleons:
- proton:
quarkContent: [u, u, d]
charge: 1
- antiproton:
quarkContent: [au, au, ad]
charge: -1
- neutron:
quarkContent: [d, d, u]
charge: 0
- antineutron:
quarkContent: [ad, ad, au]
charge: 0
? hyperons:
- lambda:
quarkContent: [u, d, s]
charge: 0
- antilambda:
quarkContent: [au, ad, as]
charge: 0
正如你所看到的,从hyperons开始,有一个问号。我尝试添加更多条目以查看会发生什么。它似乎在?
和:
之间交替出现。这很奇怪。
我尝试删除了核子键和超子键的所有内容,我仍然得到了这个
baryons:
nucleons:
- Hello
? hyperons:
- Hello
嗯。确实很奇怪。这是我的代码。原谅混乱
#include "yaml-cpp/yaml.h"
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <typeinfo>
using namespace YAML;
void addParticle(Emitter * e, std::string name, std::string qc1, std::string qc2, std::string qc3, int charge){
*e << BeginMap << Key << name;
*e << Value;
*e << BeginMap;
*e << Key << "quarkContent" << Value << Flow << BeginSeq << qc1 << qc2 << qc3 << EndSeq;
*e << Key << "charge" << Value << charge;
*e << EndMap;
*e << EndMap;
*e << BeginMap << Key << "anti" + name;
*e << Value;
*e << BeginMap;
*e << Key << "quarkContent" << Value << Flow << BeginSeq << "a" + qc1 << "a" + qc2 << "a" + qc3 << EndSeq;
*e << Key << "charge" << Value << charge * -1;
*e << EndMap;
*e << EndMap;
};
int main(){
Emitter e;
e << BeginMap;
e << Key << "baryons";
e << Value;
e << BeginMap;
e << Key << "nucleons";
e << Value;
e << BeginSeq;
addParticle(&e, "proton", "u", "u", "d", 1);
addParticle(&e, "neutron", "d", "d", "u", 0);
e << EndSeq;
e << EndMap;
e << BeginMap;
e << Key << "hyperons";
e << Value;
e << BeginSeq;
addParticle(&e, "lambda", "u", "d", "s", 0);
e << EndSeq;
e << EndMap;
e << EndMap;
std::ofstream particlesYAML;
particlesYAML.open("particles.yml");
particlesYAML.write(e.c_str(), strlen(e.c_str()));
particlesYAML.close();
return 0;
};
在旁注中,我缩进以减少混乱。也请原谅。
另外,我的YAML结构好吗?或者我应该修改一些不同的东西?感谢。
答案 0 :(得分:1)
当您真正想要一个具有两个键/值对的地图时,您将两个连续的地图写为单个节点。具体来说(这是你的代码片段):
e << BeginMap;
e << Key << "nucleons";
e << Value;
e << BeginSeq;
addParticle(&e, "proton", "u", "u", "d", 1);
addParticle(&e, "neutron", "d", "d", "u", 0);
e << EndSeq;
// you previously had a EndMap and BeginMap
e << Key << "hyperons";
e << Value;
e << BeginSeq;
addParticle(&e, "lambda", "u", "d", "s", 0);
e << EndSeq;
e << EndMap;
yaml-cpp为您提供额外?
而不是仅仅提供错误的原因是您实际上不需要提供YAML::Key
或YAML::Value
。您的代码如下:
e << YAML::BeginMap;
e << YAML::Key << "foo"; // specifies the key
e << YAML::Value;
e << YAML::BeginMap; // specifies the value
// stuff
e << YAML::EndMap;
e << YAML::BeginMap; // specifies a new key (the YAML::Key is implied)
// stuff
e << YAML::EndMap;
// no value is provided for that key
e << YAML::EndMap;
所以你有一张带有两个键/值对的地图。第一个是您的预期(键是foo
,值是地图)。但是,对于第二个,键是一个地图,并且未提供该值,因此它被解释为null
。由于密钥是地图,因此密钥必须是长格式密钥,并使用额外的?
指定。
旁注:有一个e.size()
可以为您提供输出字符串的长度,因此您无需使用strlen
。