c++ integer->std::string 转换。简单的功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/273908/
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
c++ integer->std::string conversion. Simple function?
提问by Paul Nathan
Problem: I have an integer; this integer needs to be converted to a stl::string type.
问题:我有一个整数;这个整数需要转换为 stl::string 类型。
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).
过去,我习惯stringstream
做一个转换,这只是有点麻烦。我知道 C 的方式是做一个sprintf
,但我更愿意做一个类型安全的 C++ 方法(呃)。
Is there a better way to do this?
有一个更好的方法吗?
Here is the stringstream approach I have used in the past:
这是我过去使用的 stringstream 方法:
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 noted that the invocation is pretty nice, however:
Zan 指出,调用非常好,但是:
std::string s = t_to_string(my_integer);
At any rate, a nicer way would be... nice.
无论如何,更好的方式将是......很好。
Related:
有关的:
回答by Johannes Schaub - litb
Now in c++11 we have
现在在 c++11 中我们有
#include <string>
string s = std::to_string(123);
Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string
参考链接:http: //en.cppreference.com/w/cpp/string/basic_string/to_string
回答by Mic
Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:
如前所述,我建议使用 boost lexical_cast。它不仅有一个相当不错的语法:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);
it also provides some safety:
它还提供了一些安全性:
try{
std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
...
}
回答by David Thornley
Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).
不是真的,在标准中。一些实现有一个非标准的 itoa() 函数,你可以查找 Boost 的 lexical_cast,但如果你坚持标准,它几乎是 stringstream 和 sprintf() 之间的选择(如果你有的话,snprintf())。