C++: what is the optimal way to convert a double to a string?

后端 未结 12 1772
温柔的废话
温柔的废话 2020-12-16 17:09

What is the most optimal way to achieve the same as this?

void foo(double floatValue, char* stringResult)
{
    sprintf(stringResult, \"%f\", floatV         


        
12条回答
  •  温柔的废话
    2020-12-16 17:41

    In the future, you can use std::to_chars to write code like https://godbolt.org/z/cEO4Sd . Unfortunately, only VS2017 and VS2019 support part of this functionality...

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::array chars;
        auto [parsed, error] = std::to_chars(
            chars.data(), 
            chars.data() + chars.size(), 
            static_cast(12345.234)
        );
        std::cout << std::string_view(chars.data(), parsed - chars.data());
    }
    

    For a lengthy discussion on MSVC details, see https://www.reddit.com/r/cpp/comments/a2mpaj/how_to_use_the_newest_c_string_conversion/eazo82q/

提交回复
热议问题