Categories
c++ int string type-conversion

Easiest way to convert int to string in C++

1978

What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?

(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

6

  • 6

    I think both methods you gave are good solutions. it depends on the context where you need to do it. If you’re already working with streams, for example reading or writing a file, then your second method is the best. If you need to pass an int as a string to a function argument, then itoa could be an easy way. But most of the time, int to string conversion occurs when dealing with files, so streams are appropriate.

    Apr 8, 2011 at 5:21

  • 58

    How does option 1 even work for you at all? It’s my understanding that itoa() takes three parameters.

    – arkon

    Apr 10, 2013 at 2:49

  • 2

    itoa will be faster than the stream equivalent. There are also ways of re-using the string buffer with the itoa method (avoiding heap allocations if you are frequently generating strings. e.g. for some rapidly updating numerical output). Alternatively you can generate a custom streambuf to reduce some of the allocation overhead etc. Constructing the stream in the first place is also not a low cost venture.

    – Pete

    Aug 28, 2013 at 18:46

  • 7

    @Pete: Once you start worrying about which is faster, you’ll want to look at stackoverflow.com/questions/4351371/…

    – Ben Voigt

    Sep 24, 2013 at 19:21

  • 25

    Note that itoa() is not part of the standard and therefore using it renders your code not portable since not all compilers support it. For Linux you are most certainly out unless you are using something else than GCC, which does not support this function. If you have C++0x, go with what @Matthieu has suggested in his answer. If that’s not the case, go with stringstream since it is a well supported feature and your code should be compatible with every C++ compiler out there. As an alternative you can always go with sprintf().

    Jun 16, 2014 at 9:59

2596

C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.

#include <string> 

std::string s = std::to_string(42);

is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:

auto s = std::to_string(42);

Note: see [string.conversions] (21.5 in n3242)

22

  • 217

    to_string not a member of std fix: stackoverflow.com/questions/12975341/…

    – Ben

    Nov 2, 2012 at 3:02


  • 42

    Or depending on your compiler, just set the right language standard: g++ -std=c++11 someFile.cc

    Nov 29, 2012 at 23:12

  • 15

    @Steve: it’s supposed to be. It’s a member of std in every compiler I know of except for one.

    May 31, 2013 at 21:34


  • 6

    @Matthiew M. I am using the same which you suggest but i am getting this error : Error : No instance of overloaded function "std::to_string" matches the argument list i am using VS2010 c++

    – user2643530

    Sep 26, 2013 at 13:51

  • 23

    @Flying: under VS2010 you have to explicitly cast the converting integer to one of the following types [_Longlong, _ULonglong, long double]; i.e: string s = to_string((_ULonglong)i);

    – Zac

    Dec 6, 2013 at 14:50


220

C++20 update: std::format would be the idiomatic way now.


C++17 update:

Picking up a discussion with @v.oddou a couple of years later, C++17 has finally delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro uglyness.

// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
    std::ostringstream sstr;
    // fold expression
    ( sstr << std::dec << ... << args );
    return sstr.str();
}

Usage:

int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );

Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );

Original (C++98) answer:

Since “converting … to string” is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:

#include <sstream>

#define SSTR( x ) static_cast< std::ostringstream & >( \
        ( std::ostringstream() << std::dec << x ) ).str()

Usage is as easy as could be:

int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );

Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );

The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.

10

  • 2

    I am not very familiar with dynamic_cast but I am using clang to compile so it complains about it. If I just omit the dynamic_cast then it compiles fine; what purpose does the dynamic_cast serve in this case? We are already creating an ostringstream, so why cast it?

    – Mathew

    Oct 21, 2014 at 2:38

  • 2

    @Mathew: The link in my answer leads to a detailed description of each part of the construct. While we created a ostringstream, we called operator<<() on it, which returns ostream & — for which .str() is not defined. I really wonder how clang would make this work without the cast (or why it generates an error with it). This construct is published in many places, and I’ve used it for over a decade on many different compilers, including MSVC, GCC, and XLC, so I am rather surprised clang balks at it.

    – DevSolar

    Oct 21, 2014 at 6:59

  • 9

    Just came to the party for curiosity, and downvoted. Reason : too much votes for a solution that’s un-elegant, and likely slow. 1. macro usage. I don’t systematically frown on any macro, but this one is too short, and end-clients always fear repetition of the argument, on top of fear for unprotected multilines macros. (not protected by do{}while(0)) 2. dynamic_cast. it seems you only need a static_cast here, unless you want to assert that the library indeed is implemented as you hope. in which case you should use boost::polymorphic_downcast instead.

    – v.oddou

    Jun 18, 2015 at 3:30

  • 2

    @v.oddou: You’re free to critizise, of course. But 1. is invalid — the macro is a single statement, do { } while( 0 ) would not add anything. With 2. and 3. you probably got a point — this could be done with a static cast, and perhaps one of you template wizards out there could come up with a “nicer” interface. But as I said, this is by no means an invention of myself. Look around, this macro (macro!) is quite ubiquitous. That’s a case of POLA in itself. I might toy with this a bit to make it more “streamlined”.

    – DevSolar

    Jun 18, 2015 at 8:45

  • 1

    @v.oddou: Look at what I found among the things C++17 brought us. 🙂 I hope you like the updated answer.

    – DevSolar

    May 13, 2018 at 20:57

128

Current C++

Starting with C++11, there’s a std::to_string function overloaded for integer types, so you can use code like:

int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);

The standard defines these as being equivalent to doing the conversion with sprintf (using the conversion specifier that matches the supplied type of object, such as %d for int), into a buffer of sufficient size, then creating an std::string of the contents of that buffer.

Old C++

For older (pre-C++11) compilers, probably the most common easy way wraps essentially your second choice into a template that’s usually named lexical_cast, such as the one in Boost, so your code looks like this:

int a = 10;
string s = lexical_cast<string>(a);

One nicety of this is that it supports other casts as well (e.g., in the opposite direction works just as well).

Also note that although Boost lexical_cast started out as just writing to a stringstream, then extracting back out of the stream, it now has a couple of additions. First of all, specializations for quite a few types have been added, so for many common types, it’s substantially faster than using a stringstream. Second, it now checks the result, so (for example) if you convert from a string to an int, it can throw an exception if the string contains something that couldn’t be converted to an int (e.g., 1234 would succeed, but 123abc would throw).

2

  • 2

    Nice, I prefer Kevin’s answer, though as he shows the include and namespace. Just a minor gripe. 🙂 Good job, though!

    Mar 21, 2013 at 14:15


  • 5

    I’d say this is the way to go if you don’t have C++11 support.

    Jun 21, 2013 at 8:16