C++ 将 `double` 转换为 `string`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19690630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting `double` to `string`
提问by Plamen
I am implementing this:
我正在实施这个:
double x;
ostringstream x_convert;
x_convert << x;
string x_str = x_convert.str();
It seems a bit superfluous. Is there a more elegant way?
似乎有点多余。有没有更优雅的方式?
回答by Barry
Are you using C++11? If so, there's:
你在使用 C++11 吗?如果是这样,有:
auto x_str = std::to_string(x);
回答by 0x499602D2
回答by Zac Howland
What you have is the safestmethod (pre-C++11).
您拥有的是最安全的方法(C++11 之前)。
Alternatively, you could so something like:
或者,你可以这样:
double value = SOME_VALUE;
char buffer[100] = {};
sprintf(buffer, "%f", value);
std::string s = buffer;
Which is functionally equivalent to what std::to_string
does. You must be careful to have enough space allocated for buffer
, and (as you can see), you are still writing about 4 lines of code to do this conversion, so it is no more (nor less) elegant than the other methods.
这在功能上等同于什么std::to_string
。您必须小心为buffer
,分配足够的空间,并且(如您所见),您仍在编写大约 4 行代码来执行此转换,因此它并不比其他方法更优雅(也不逊色)。
If you are stuck in pre-C++11, you can implement your own to_string
by doing something like:
如果您被困在 C++11 之前,您可以to_string
通过执行以下操作来实现自己的:
template<typename T>
std::string to_string(T t)
{
std::ostringstream oss;
oss << t;
return oss.str();
}
Which will work for any type that already has an overload for std::ostream& operator<<(std::ostream&, T&)
.
这将适用于任何已经有std::ostream& operator<<(std::ostream&, T&)
.
回答by vz0
Without C++11 you may write your own to_string
function:
如果没有 C++11,您可以编写自己的to_string
函数:
string to_string(double x) {
ostringstream x_convert;
x_convert << x;
return x_convert.str();
}
回答by John Dibling
With C++11, as mentioned by others, use std::to_string
.
正如其他人所提到的,在 C++11 中,使用std::to_string
.
Without C++11, you are stuck with the code you've already written, or something along those lines. You can make the use of that code a bit more elegant (read: less typing) by constructing a device which does the string building for you:
如果没有 C++11,你会被你已经编写的代码或类似的东西困住。您可以通过构建一个为您构建字符串的设备来更优雅地使用该代码(阅读:少打字):
class StringBuilder
{
public:
template <typename T> inline StringBuilder& operator<<(const T& t)
{
mStream << t;
return * this;
}
inline std::string get() const
{
return mStream.str();
}
inline operator std::string () const
{
return get();
}
private:
std::stringstream mStream;
};
Now you can:
现在你可以:
double x;
string x_str = StringBuilder() << x;
But at the end of the day it's really just syntactic sugar for the same thing. There are similar devices in Boost -- I'd use those if you can.
但归根结底,它实际上只是同一件事的语法糖。Boost 中有类似的设备——如果可以的话,我会使用它们。