Parsing a Very Simply Config File

给你一囗甜甜゛ 提交于 2019-12-11 18:50:03

问题


I am writing a OBDII reading library / application in C++. Data is retrieved from the car's computer by sending a simple string command, then passing the result through a function specific to each parameter.

I would like to read a config file of all the commands I want, something like this perhaps:

Name, Command, function

Engine RPM, 010C, ((256*A)+B)/4
Speed, 010D, A

Basically, very simple, all data needs to just be read in as a string. Can anyone recommend a good simple library for this? My target is g++ and/ or Clang on Linux if that matters.


回答1:


You could use std::ifstream to read line by line, and boost::split to split the line by ,.

Sample code:

You could check tokens size for sanity checks of file loaded.

#include <fstream>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>

int main(int argc, char* argv[]) {
    std::ifstream ifs("e:\\save.txt");

    std::string line;
    std::vector<std::string> tokens;
    while (std::getline(ifs, line)) {
        boost::split(tokens, line, boost::is_any_of(","));
        if (line.empty())
            continue;

        for (const auto& t : tokens) {
            std::cout << t << std::endl;
        }
    }

    return 0;
}

You could also use String Toolkit Library if you don't want to implemented. Docs



来源:https://stackoverflow.com/questions/24918394/parsing-a-very-simply-config-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!