Simple string parsing with C++

前端 未结 6 1071
感情败类
感情败类 2020-12-04 10:22

I\'ve been using C++ for quite a long time now but nevertheless I tend to fall back on scanf when I have to parse simple text files. For example given a config

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 11:00

    The C++ String Toolkit Library (StrTk) has the following solution to your problem:

    #include 
    #include 
    #include "strtk.hpp"
    
    int main()
    {
       std::string file_name = "simple.txt";
       strtk::for_each_line(file_name,
                           [](const std::string& line)
                           {
                              std::deque token_list;
                              strtk::parse(line,"[]: ",token_list);
                              if (token_list.empty()) return;
    
                              const std::string& key = token_list[0];
    
                              if (key == "foo")
                              {
                                //do 'foo' related thing with token_list[1] 
                                //and token_list[2]
                                return;
                              }
    
                              if (key == "bar")
                              {
                                //do 'bar' related thing with token_list[1]
                                return;
                              }
    
                           });
    
       return 0;
    }
    

    More examples can be found Here

提交回复
热议问题