问题:我有一个整数; 该整数需要转换为stl :: string类型。
在过去,我已经使用stringstream进行转换,这只是一种麻烦。 我知道C的方式是做一个sprintf ,但是我宁愿做一个类型安全的(C ++)方法。
有更好的方法吗?
以下是我过去使用的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()将整数转换为字符串C ++?
Problem: I have an integer; this integer needs to be converted to a stl::string type.
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 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.
Related:
Alternative to itoa() for converting integer to string C++?
最满意答案
现在在c ++ 11我们有
#include <string> string s = std::to_string(123);链接到参考: http : //en.cppreference.com/w/cpp/string/basic_string/to_string
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
更多推荐
发布评论