Simple string parsing with C++

前端 未结 6 1083
感情败类
感情败类 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 10:49

    Boost.Spirit is not reserved to parse complicated structure. It is quite good at micro-parsing too, and almost match the compactness of the C + scanf snippet :

    #include 
    #include 
    #include 
    
    using namespace boost::spirit::qi;
    
    
    int main()
    {
       std::string text = "foo: [3 4 5]\nbaz: 3.0";
       std::istringstream iss(text);
    
       std::string line;
       while (std::getline(iss, line))
       {
          int x, y, z;
          if(phrase_parse(line.begin(), line.end(), "foo: [">> int_ >> int_ >> int_ >> "]", space, x, y, z))
             continue;
          float w;
          if(phrase_parse(line.begin(), line.end(), "baz: ">> float_, space , w))
             continue;
       }
    }
    

    (Why they didn't add a "container" version is beyond me, it would be much more convenient if we could just write :

    if(phrase_parse(line, "foo: [">> int_ >> int_ >> int_ >> "]", space, x, y, z))
       continue;
    

    But it's true that :

    • It adds a lot of compile time overhead.
    • Error messages are brutal. If you make a small mistake with scanf, you just run your program and immediately get a segfault or an absurd parsed value. Make a small mistake with spirit and you will get hopeless gigantic error messages from the compiler and it takes a LOT of practice with boost.spirit to understand them.

    So ultimately, for simple parsing I use scanf like everyone else...

提交回复
热议问题