C ++ integer & # 8594; std :: string. Simple function?

Problem: I have an integer; this integer needs to be converted to type stl :: string.

In the past, I used stringstream to convert, and it's just cumbersome. I know that the C-way is to do sprintf , but I'd rather do C ++ - a method that is typafe (er).

Is there a better way to do this?

Below is the stringstream method I 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 follows:

 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 an opinion that this is a rather "hard" implementation.

Zan noticed that the call is pretty nice:

 std::string s = t_to_string(my_integer); 

Anyway, the best way would be ... nice.

Connected:

Alternative to itoa () to convert integer to C ++ string?

+73
c ++ stdstring integer
Nov 07 '08 at 22:52
source share
3 answers

Now in C ++ 11 we have

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

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

+129
Dec 02 2018-11-12T00:
source share

As mentioned earlier, I would recommend increasing lexical_cast. Not only does it have pretty good syntax:

 #include <boost/lexical_cast.hpp> std::string s = boost::lexical_cast<std::string>(i); 

it also provides some security:

 try{ std::string s = boost::lexical_cast<std::string>(i); }catch(boost::bad_lexical_cast &){ ... } 
+28
Nov 07 '08 at 23:14
source share

Not really, in the standard. Some implementations have the non-standard itoa () function, and you can search for Boost lexical_cast, but if you adhere to the standard, it's a pretty big choice between stringstream and sprintf () (snprintf (), if you have one).

+22
Nov 07 '08 at 22:55
source share



All Articles