How to parse a string to an int in C++?

前端 未结 17 1714
忘了有多久
忘了有多久 2020-11-21 11:01

What\'s the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).

17条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 12:03

    I think these three links sum it up:

    • http://tinodidriksen.com/2010/02/07/cpp-convert-int-to-string-speed/
    • http://tinodidriksen.com/2010/02/16/cpp-convert-string-to-int-speed/
    • http://www.fastformat.org/performance.html

    stringstream and lexical_cast solutions are about the same as lexical cast is using stringstream.

    Some specializations of lexical cast use different approach see http://www.boost.org/doc/libs/release/boost/lexical_cast.hpp for details. Integers and floats are now specialized for integer to string conversion.

    One can specialize lexical_cast for his/her own needs and make it fast. This would be the ultimate solution satisfying all parties, clean and simple.

    Articles already mentioned show comparison between different methods of converting integers <-> strings. Following approaches make sense: old c-way, spirit.karma, fastformat, simple naive loop.

    Lexical_cast is ok in some cases e.g. for int to string conversion.

    Converting string to int using lexical cast is not a good idea as it is 10-40 times slower than atoi depending on the platform/compiler used.

    Boost.Spirit.Karma seems to be the fastest library for converting integer to string.

    ex.: generate(ptr_char, int_, integer_number);
    

    and basic simple loop from the article mentioned above is a fastest way to convert string to int, obviously not the safest one, strtol() seems like a safer solution

    int naive_char_2_int(const char *p) {
        int x = 0;
        bool neg = false;
        if (*p == '-') {
            neg = true;
            ++p;
        }
        while (*p >= '0' && *p <= '9') {
            x = (x*10) + (*p - '0');
            ++p;
        }
        if (neg) {
            x = -x;
        }
        return x;
    }
    

提交回复
热议问题