LoginSignup
1
1

More than 5 years have passed since last update.

C++でtext fileをparsingしたい人生だった

Last updated at Posted at 2015-05-29

※書きかけです
まずうちさぁ…デリミタで区切られたパラメーターファイルがあるんだけど、読んでかない?


こういう感じのパラメーターファイル

OUTPUT_DIR=result
MODE=1

みたいなファイルを読みたいなぁと思いまして、これがperlなら

open (DAT, "param.txt");
my @param = <DAT>;
close DAT;
foreach(@param){
    chomp;
    my($key, $val) = split/=/,$_;
}

みたいなのでおすぃまいなんだけれど、
C++でこれと同じような事をやろうとすると複雑だったのでメモ。


#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>

class ParamFile{
    std::map<std::string, std::string> param;
    public:
    ParamFile(const char* const file){
        std::ifstream input;
        input.open(file, std::ios::in);
        if(input.fail() == true){
            std::cout << "Cannot open file..." << std::endl;
            return;
        }
        std::string line;
        while(std::getline(input, line)){
            //comment out
            if(line[0] == '#') continue;
            //empty line
            if(line.empty() == true) continue;
            //make stream
            std::istringstream stream(line);
            std::string tmp;
            std::vector<std::string> keyval;
            while(std::getline(stream, tmp, '=')){
                keyval.push_back(tmp);
            }
            param.insert(std::map<std::string, std::string>::value_type(keyval[0], keyval[1]));
        }
        input.close();
    }
    void show(){
        for(std::map<std::string, std::string>::iterator it = param.begin() ; it != param.end() ; ++ it){
            std::cout << it->first << " = " << it->second << std::endl;
        }
    }
    std::string getValueOf(std::string key){
        return param[key];
    }
    /*
    template <typename type> type getValueOf(std::string key){
        return 1;
    }
    */
};

ParamFileのインスタンスを作ってコンストラクタでread fileを突っ込む。
getValueOf(key)でkeyの値が帰ってくるという感じ。
このままだと全部string型で帰ってくるので、
そのうちテンプレートパラメータでもって数値に変換して返したり出来るようにしたいところ。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1