2017-07-27 32 views
0

我對yaml-cpp很新。之後做了tutorials,那個教程很好。但是當我嘗試解析我自己的yaml文件時,對我來說這是一個很小的困難。我很困惑「運營商」和「節點」。
yaml文件如下所示。yaml-cpp 0.5.3在linux中的示例

Device: 
    DeviceName: "/dev/ttyS2" 
    Baud: 19200 
    Parity: "N" 
    DataBits: 8 
    StopBits: 1 
Control: 
    Kp: 5000 
    Ki: 8 
    FVF: 100 
    VFF: 1962 

你能給我一個例子從yaml文件中獲取數據嗎?謝謝你的幫助。 我也跟着這個question,我可以建立它。但是當我運行它,我得到分割故障(核心轉儲) 代碼

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

using namespace std; 

int main() 
{ 
    YAML::Node config = YAML::LoadFile("init.yaml"); 
    //read device 
    std::string DeviceName = config["Device"][0]["DeviceName"].as<std::string>(); 
    int   Baud  = config["Device"][1]["Baud"].as<int>(); 
    std::string Parity  = config["Device"][2]["Parity"].as<std::string>(); 
    int   DataBits = config["Device"][3]["DataBits"].as<int>(); 
    int   StopBits = config["Device"][4]["StopBits"].as<int>(); 

    //read control 
    int Kp = config["Control"][0]["Kp"].as<int>(); 
    int Ki = config["Control"][1]["Ki"].as<int>(); 
    int FVF = config["Control"][2]["FVF"].as<int>(); 
    int VFF = config["Control"][3]["VFF"].as<int>(); 

    cout <<"DeviceName" << DeviceName << endl; 
    cout <<"Baud"  << Baud  << endl; 
    cout <<"Parity"  << Parity  << endl; 
    cout <<"DataBits" << DataBits << endl; 
    cout <<"StopBits" << StopBits << endl; 

    cout <<"Kp" << Kp << endl; 
    cout <<"Ki" << Ki << endl; 
    cout <<"FVF" << FVF << endl; 
    cout <<"VFF" << VFF << endl; 
    return 0; 
} 
+0

請發表您使用的代碼。 –

+0

@JesseBeder,對於非常遲的回覆感到抱歉。請給我一些建議。想 – crazymumu

回答

0

代碼上面不好的轉換異常的結果,因爲你在一個錯誤的方式訪問地圖項目。

代替

std::string DeviceName = config["Device"][0]["DeviceName"].as<std::string>(); 

只寫

std::string DeviceName = config["Device"]["DeviceName"].as<std::string>(); 

問候 羅伯特