将双精度转换为字符串函数-内存问题

Converting double to string function - memory issues?

本文关键字:内存 问题 函数 字符串 双精度 转换      更新时间:2023-10-16

我发现自己不得不std::cout各种双变量。我编写了一个简单的函数,将双精度类型转换为std::string,然后可以将其与std::cout等一起使用。

// Convert a double to a string.
std::string dtos(double x) {
    std::stringstream s;
    s << x;
    return s.str();
}

该函数似乎可以正常工作,但我的问题是:这种方法是否有任何(坏的)内存影响。我是否分配了不必要的内存,或者留下了什么"悬空"?

谢谢皮特

不,你的代码是好的,阅读代码上的注释:

std::string dtos(double x) {
    std::stringstream s;  // Allocates memory on stack
    s << x;
    return s.str();       // returns a s.str() as a string by value
                          // Frees allocated memory of s
} 

另外,您可以直接将double传递给cout

令人惊讶的是没有人提到这一点,但您可以使用模板将该算法推广到任何类型。

一样:

template<typename T>
std::string to_string(const T& obj)
{
    std::ostringstream s;
    s << obj;
    return s.str();
}

这样可以很容易地转换为字符串,如下所示:

int x = 5;
to_string(x); // will convert the integer to a string
to_string(32); // constants works
to_string<double>(302); // you can explicitly type the type you wish to convert

示例用法在此链接。

另外,正如其他人所说的,内存没有去任何地方。另外,我想提到的是,既然你只写字符串流,也许你应该使用std::ostringstream来(1)在人们阅读你的代码时进一步澄清(2)避免使用>>而不是<<

的错误

你不必改变双元组字符串使用std::cout

cout << x; 

一样好
cout << dtos(x); 

如果你想把double类型改成string类型,你可以使用c++ 11中的std::to_string

除此之外,你的代码就很好了。