What's the difference between std::to_string, boost::to_string, and boost::lexical_cast?

后端 未结 3 1855
半阙折子戏
半阙折子戏 2021-02-12 10:41

What\'s the purpose of boost::to_string (found in boost/exception/to_string.hpp) and how does it differ from boost::lexical_cast

3条回答
  •  你的背包
    2021-02-12 11:36

    There are more differences: boost::lexical_cast works a bit different when converting double to string. Please consider the following code:

    #include 
    #include 
    
    #include "boost/lexical_cast.hpp"
    
    int main()
    {
        double maxDouble = std::numeric_limits::max();
        std::string str(std::to_string(maxDouble));
    
        std::cout << "std::to_string(" << maxDouble << ") == " << str << std::endl;
        std::cout << "boost::lexical_cast(" << maxDouble << ") == "
                  << boost::lexical_cast(maxDouble) << std::endl;
    
        return 0;
    }
    

    Results

    $ ./to_string
    std::to_string(1.79769e+308) == 179769313486231570814527423731704356798070600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000
    boost::lexical_cast(1.79769e+308) == 1.7976931348623157e+308
    

    As you can see, the boost version uses exponential notation (1.7976931348623157e+308) whereas std::to_string prints every digit, and six decimal places. One may be more useful than another for your purposes. I personally find the boost version more readable.

提交回复
热议问题