Alternative to boost::lexical_cast

后端 未结 7 1155
粉色の甜心
粉色の甜心 2020-12-30 06:27

I\'m taking a part in a challenge, and just to cut to the point, in one of places in my program I need to convert string to an integer. I\'ve tried boost::lexical_cast but u

7条回答
  •  天命终不由人
    2020-12-30 06:46

    I can recommend Boost Spirit (parse with Qi):

    1. some benchmarks
      • https://cppsoup.wordpress.com/2010/01/08/boost-spirit-v2-x-versus-cs-atoi/
      • karma benchmark in documentation
    2. See also my other answer atoi on a character array with lots of integers
    3. some sample uses:

    .

    #include 
    
    namespace qi = boost::spirit::qi;
    
    
    const char *demo1 = "1234";
    const char *demo2 = "1234,2345,-777,-888";
    const char *demo3 = " 1234 , 2345 , -777, -888  ";
    
    void do_demo1()
    {
        const char *begin = demo1;
        const char *iter  = begin;
        const char *end   = demo1+strlen(demo1);
        int result;
    
        if (qi::parse(iter, end, qi::int_, result))
            std::cout << "result = " << result << std::endl;
        else 
            std::cout << "parse failed at #" << (iter - begin) << ": " << std::string(iter, end) << std::endl;
    
        //// to allow for spaces, use phrase_parse instead of parse
        // if (qi::phrase_parse(begin, end, qi::int_, qi::space, result)
                //// ... etc
    }
    
    void do_demo2()
    {
        const char *begin = demo2;
        const char *iter  = begin;
        const char *end   = demo2+strlen(demo2);
        std::vector results;
    
        if (qi::parse(iter, end, qi::int_ % ',', results))
             std::cout << "results = " << results.size() << std::endl;
        else 
            std::cout << "parse failed at #" << (iter - begin) << ": " << std::string(iter, end) << std::endl;
    }
    
    void do_demo3()
    {
        const char *begin = demo3;
        const char *iter  = begin;
        const char *end   = demo3+strlen(demo3);
        std::vector results;
    
        if (qi::phrase_parse(iter, end, qi::int_ % ',', qi::space, results))
             std::cout << "results = " << results.size() << std::endl;
        else std::cout << "parse failed at #" << (iter - begin) << ": " << std::string(iter, end) << std::endl;
    }
    
    int main()
    {
        do_demo1();
        do_demo2();
        do_demo3();
        return 0;
    }
    

    Other

    Be sure to look at binary (de)serialization IFF you can dictate the stream (text) format. See my recent answer here for a comparison of methods when aimed at serializing/deserializing:

    • STL (unadorned ANSI C++98 standard library)
    • Boost Spirit (above)
    • Boost Serialization

    That post includes benchmarks

提交回复
热议问题