77

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++?

Community
  • 1
  • 1
Paul Nathan
  • 39,638
  • 28
  • 112
  • 212
  • In your example t_to_string I fail to see why a template specification is required. A template function can determine its template type from its argument types. – Zan Lynx Jul 28 '10 at 22:06
  • @Zan: Durp. That's what I get for posting code I didn't compile. – Paul Nathan Jul 28 '10 at 22:13
  • 13
    How about some of the examples from the following: http://www.codeproject.com/KB/recipes/Tokenizer.aspx They are very efficient and somewhat elegant. –  Nov 02 '10 at 05:01
  • @Beh: That library is considerably heavier-weight than a simple t_to_string(). It actually looks like a very nice library, but I wouldn't want to import the whole thing for just doing a t_to_string(). – Paul Nathan Nov 08 '10 at 17:38

3 Answers3

136

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

tanguy_k
  • 11,307
  • 6
  • 54
  • 58
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
28

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 &){
 ...
}
tanguy_k
  • 11,307
  • 6
  • 54
  • 58
Mic
  • 6,741
  • 3
  • 24
  • 25
22

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

David Thornley
  • 56,304
  • 9
  • 91
  • 158
  • 2
    Good thing this has been fixed, see [Schaub's answer](http://stackoverflow.com/questions/273908/c-integer-stdstring-conversion-simple-function#8362045) – sehe May 16 '12 at 08:00