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

后端 未结 12 1774
温柔的废话
温柔的废话 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:22

    I'm sure someone will say boost::lexical_cast, so go for that if you're using boost, but it's basically the same as this anyway:

     #include 
     #include 
    
     std::string doubleToString(double d)
     {
        std::ostringstream ss;
        ss << d;
        return ss.str();
     }
    

    Note that you could easily make this into a template that works on anything that can be stream-inserted (not just doubles).

提交回复
热议问题