字符串转换。简单的函数?

问题: 我有一个整数; 这个整数需要转换为 stl: : string 类型。

在过去,我使用 stringstream进行转换,这有点麻烦。我知道 C 方法是执行 sprintf,但是我更愿意执行类型安全的 C + + 方法。

还有更好的办法吗?

下面是我过去使用过的字符串方法:

std::string intToString(int i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();


return s;
}

当然,这可以改写为:

template<class T>
std::string t_to_string(T i)
{
std::stringstream ss;
std::string s;
ss << i;
s = ss.str();


return s;
}

然而,我认为这是一个相当“重量级”的实现。

然而,Zan 指出,这个调用相当不错:

std::string s = t_to_string(my_integer);

无论如何,一个更好的方式将是... 好。

相关阅读:

替代 itoa ()将整数转换为字符串 C + + ?

111380 次浏览

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).

Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:

#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 &){
...
}

Now in c++11 we have

#include <string>
string s = std::to_string(123);

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string