c++ 整数->std::string 转换.简单的功能?
问题:我有一个整数;这个整数需要转换为 stl::string 类型.
Problem: I have an integer; this integer needs to be converted to a stl::string type.
过去,我使用 stringstream
进行转换,这有点麻烦.我知道 C 方法是执行 sprintf
,但我更愿意执行类型安全的 C++ 方法.
In the past, I've used stringstream
to do a conversion, and that's just kind of cumbersome. I know the C way is to do a sprintf
, but I'd much rather do a C++ method that is typesafe(er).
有没有更好的方法来做到这一点?
Is there a better way to do this?
这是我过去使用的字符串流方法:
Here is the stringstream approach I have used in the past:
std::string intToString(int i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();
return s;
}
当然,这可以改写成这样:
Of course, this could be rewritten as so:
template<class T>
std::string t_to_string(T i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();
return s;
}
但是,我认为这是一个相当重量级"的实现.
However, I have the notion that this is a fairly 'heavy-weight' implementation.
Zan 注意到调用非常好,但是:
Zan noted that the invocation is pretty nice, however:
std::string s = t_to_string(my_integer);
无论如何,更好的方法是......很好.
At any rate, a nicer way would be... nice.
itoa() 的替代方法,用于将整数转换为字符串 C++?
推荐答案
现在在 c++11 中我们有了
Now in c++11 we have
#include <string>
string s = std::to_string(123);
参考链接:http://en.cppreference.com/w/cpp/string/basic_string/to_string
相关文章