c ++ integer-> std :: string转换。 简单的function?
问题:我有一个整数; 这个整数需要转换成stl :: stringtypes。
在过去,我已经使用了stringstream进行转换,这只是一种麻烦。 我知道C的方式是做一个sprintf ,但我宁愿做一个C ++的方法是types安全(呃)。 
有一个更好的方法吗?
以下是我过去使用的stringstream方法:
 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; } 
但是,我认为这是一个相当“重量级”的实现。
赞指出,调用是相当不错,但是:
 std::string s = t_to_string(my_integer); 
无论如何,更好的方法是…好。
有关:
替代itoa()将整数转换为stringC ++?
现在在C ++ 11中,我们有
 #include <string> string s = std::to_string(123); 
链接到引用: http : //en.cppreference.com/w/cpp/string/basic_string/to_string
就像之前提到的,我build议增加lexical_cast。 它不仅具有相当好的语法:
 #include <boost/lexical_cast.hpp> std::string s = boost::lexical_cast<std::string>(i); 
它也提供了一些安全性:
 try{ std::string s = boost::lexical_cast<std::string>(i); }catch(boost::bad_lexical_cast &){ ... } 
不是真的,在标准中。 一些实现有一个非标准的itoa()函数,你可以查找Boost的lexical_cast,但是如果你坚持这个标准,那么在stringstream和sprintf()(snprintf()如果你有这个select的话)。