问题描述
我想从 yaml 文件中读取向量,但是当我尝试这样做时,出现以下错误
在抛出 'YAML::TypedBadConversion<:vector std::allocator> >' 实例后调用终止 what():错误的转换 中止(核心转储)
我的主程序是
bool fileLoaded = false;
YAML::Node config;
std::vector<double> target_jpos;
try
{
config = YAML::LoadFile("/config/test.yaml");
fileLoaded = true;
}
catch(std::exception& e)
{
fileLoaded = false;
}
target_jpos = config["target_jpos"].as<std::vector<double> >();
if(fileLoaded)
std::cout << "File loaded successfully \n\t target_jpos[0]: " << target_jpos[0] << "\n";
else
std::cout << "File Failed to load\n";
我的 test.yaml 文件是
target_jpos: [-0.6,-1.0,2.7,0.6,-0.6,2.7]
一切看起来都不错,但不知道为什么我会收到这个错误。有人对解决这个问题有任何想法吗?
编辑: 我的 CMakeLists.txt 是
cmake_minimum_required(VERSION 3.5)
add_subdirectory(yaml-cpp)
set(CMAKE_CXX_FLAGS "-std=c++11")
add_executable(yaml-parser main.cpp)
target_link_libraries(yaml-parser yaml-cpp)
我的树结构是
├── CMakeLists.txt
├── config
│ └── test.yaml
├── main.cpp
└── yaml-cpp
编辑:这是完整程序的 link。
解决方法
错误表明您正在尝试访问错误的类型。在我使用 yaml-cpp 时,我只使用了 float
s,并且它们运行良好。也许图书馆不支持 double
s?
试试:
std::vector<float> target_jpos;
target_jpos = config["target_jpos"].as<std::vector<float>>();
,
问题是您在检查文件是否已成功加载之前尝试从 YAML::Node
中提取数据。负载抛出异常,因此您的检查已完成。始终在使用数据之前检查是否成功。
另一方面,您可以通过将 YAML 文件更改为:
---
target_jpos: [-0.6,-1.0,2.7,0.6,-0.6,2.7]