221

What is the shortest way, preferably inline-able, to convert an int to a string? Answers using stl and boost will be welcomed.

Amir Rachum
  • 76,817
  • 74
  • 166
  • 248
  • 2
    Related: [Alternative to itoa() for converting integer to string C++?](http://stackoverflow.com/questions/228005/alternative-to-itoa-for-converting-integer-to-string-c) – moinudin Jan 12 '11 at 13:02
  • 77
    In C++11 you can use [`to_string`](http://en.cppreference.com/w/cpp/string/basic_string/to_string) like `std::string s = std::to_string(42)` –  Apr 24 '13 at 10:02
  • 6
    Long live C++11 and to_string! :) – augustin Feb 19 '15 at 15:54
  • 1
    Possible duplicate of [Easiest way to convert int to string in C++](http://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c) – UmNyobe Dec 17 '15 at 15:21

12 Answers12

465

You can use std::to_string in C++11

int i = 3;
std::string str = std::to_string(i);
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
50
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());
Benoit
  • 76,634
  • 23
  • 210
  • 236
  • This is good to also include techniques for pre-C++11. Can this code also be written as: `std::ostringstream().operator<<(i).str()`? – kevinarpe Aug 09 '21 at 13:38
38

Well, the well known way (before C++11) to do that is using the stream operator :

#include <sstream>

std::ostringstream s;
int i;

s << i;

std::string converted(s.str());

Of course, you can generalize it for any type using a template function ^^

#include <sstream>

template<typename T>
std::string toString(const T& value)
{
    std::ostringstream oss;
    oss << value;
    return oss.str();
}
neuro
  • 14,948
  • 3
  • 36
  • 59
37

boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp

Work's for everything with std::ostream support, but is not as fast as, for example, itoa

It even appears to be faster than stringstream or scanf:

Catskul
  • 17,916
  • 15
  • 84
  • 113
ltjax
  • 15,837
  • 3
  • 39
  • 62
  • 16
    Boost is your friend, if there wasn't a simple way of doing this in Standard C++... I of course like what `lexical_cast` brings, but feel Boost is pretty much overkill for this kind of tasks... – rubenvb Jan 12 '11 at 13:06
  • 2
    Overkill? Based on what? http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast/performance.html – Catskul Jun 03 '13 at 22:34
  • 1
    Should consider your audience if they are unable to use Boost – Damian Feb 26 '16 at 23:49
  • 6
    "Answers using stl and boost will be welcomed." - Audience considered – Conrad Jones Oct 08 '17 at 17:45
20

If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:

std::string to_string( int value ) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.

Implementation

#include <cstdio>
#include <string>
#include <cassert>

std::string to_string( int x ) {
  int length = snprintf( NULL, 0, "%d", x );
  assert( length >= 0 );
  char* buf = new char[length + 1];
  snprintf( buf, length + 1, "%d", x );
  std::string str( buf );
  delete[] buf;
  return str;
}

You can do more with it. Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.

user2622016
  • 6,060
  • 3
  • 32
  • 53
15

Non-standard function, but its implemented on most common compilers:

int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);

Update

C++11 introduced several std::to_string overloads (note that it defaults to base-10).

Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • 3
    @DevSolar: You should elaborate. The boost example had already been given. This solution is available on most compilers when boost is not installed (or your requirements prohibit you from using it for whatever reason). The `ostream` works as well, until you need to save the number-string as something other than a binary, octal, or hex format (e.g. base-32). – Zac Howland Jan 12 '11 at 13:08
  • 3
    I don't like it when non-standard functions like `itoa()` or `stricmp()` are given as the answer to *anything*. – DevSolar Jan 12 '11 at 13:23
  • 6
    Sorry to offend your sensibilities, but I did state it was a non-standard function in the first sentence. I didn't mention it, but `sprintf` can also accomplish the goal of the OP (though still suffers from the lack of flexibility if anything other than the common base numbers is needed). – Zac Howland Jan 12 '11 at 14:14
  • 1
    Yes you did state it, and I didn't downvote your answer, even when it itched me to do so. So I think we're even. ;-) – DevSolar Jan 12 '11 at 16:00
8

The following macro is not quite as compact as a single-use ostringstream or boost::lexical_cast.

But if you need conversion-to-string repeatedly in your code, this macro is more elegant in use than directly handling stringstreams or explicit casting every time.

It is also very versatile, as it converts everything supported by operator<<(), even in combination.

Definition:

#include <sstream>

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

Explanation:

The std::dec is a side-effect-free way to make the anonymous ostringstream into a generic ostream so operator<<() function lookup works correctly for all types. (You get into trouble otherwise if the first argument is a pointer type.)

The dynamic_cast returns the type back to ostringstream so you can call str() on it.

Use:

#include <string>

int main()
{
    int i = 42;
    std::string s1 = SSTR( i );

    int x = 23;
    std::string s2 = SSTR( "i: " << i << ", x: " << x );
    return 0;
}
DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • 1
    @rubenvb: You tell me how to turn this into a template and I'll update all the C++ projects I've been using this construct in. – DevSolar Jan 12 '11 at 13:25
  • @rubenvb: Sorry, that was not as clear as it should have been. I do not see a way how I could turn this into a template (using C++98) without either losing the ability to daisy-chain outputs (as in my second example), or having to come up with a convoluted mess to handle any number of parameters and parameter types. – DevSolar Jan 12 '11 at 13:48
  • @DevSolar: wouldn't `inline template std::string SSTR( T x ) { return dynamic_cast< std::ostringstream & >( (std::ostringstream() << std::dec << x) ).str() }` do? (Haven't tested, but I do wonder what would go wrong and why? – rubenvb Jan 12 '11 at 14:20
  • @rubenvb: It would do for an individual `int` (my first example). But without the `ostream` visible to the compiler in `main` (as it is hidden within the template function), it will try to look up `operator<<()` for `const char []` in my second example - which will croak. I know the OP asked only for an `int`, but this more generic macro is so useful (and actually quite widespread) that I thought I'd include it here. – DevSolar Jan 12 '11 at 15:59
  • For the versatility I prefer a template function. For the daisy-chain perhaps that can be handled in the same function with a bit of RTTI ... – neuro Jan 12 '11 at 16:02
  • @neuro: Well, write one up. I for one dislike macros myself, but this one is quite well-defined and well-behaving. And if the alternative is some as-yet-unavailable template function that "somehow" does the trick with lots of additional code *and* a reliance on RTTI, I believe the fine line between good practice ("avoid macros where possible") and fundamentalism ("avoid macros AT ALL COSTS!") has been crossed. – DevSolar Jan 12 '11 at 16:12
  • @DevSolar: Well daisychaining is nice, but I would write it like this: `std::string s2( "i: " + SSTR(i) + ", x: " + SSTR(x) );` which in my opinion is faster (less streaming operators) and more expressive (you're not passing everything, including the `const char*` s to the function in question. What I love C++ for these pedantic discussions `;)` – rubenvb Jan 12 '11 at 16:36
  • @rubenvb: Less streaming operators? Yes, one less. (You still have the std::dec in there.) Four streaming operators as opposed to my five. At the cost of an additional temporary `ostringstream` object, an additional `str()` call, and three `operator+()` calls, and it gets worse the longer the daisy-chain gets. ;-) Plus, I don't get what you are talking about re "passing everything to the function in question". I do not see where you are saving anything in that ballpark. – DevSolar Jan 12 '11 at 16:56
  • @DevSolar: Well, your macro is streaming everything right of the last stream operator inside it (ie the `const char*` s are also passed to the function/macro in question). Well, I may well be wrong here, but still, I did provide an inline function template alternative IMHO. – rubenvb Jan 12 '11 at 17:16
  • @rubenvb: I think there is some misunderstanding of the inner workings going on here, on your side. It's a macro, so there is no "passing". And as I said, my macro allows daisy-chaining, which is how streams are supposed to work in C++. Your template, on the other hand, does not, and is thus not a viable replacement IMHO. – DevSolar Jan 12 '11 at 19:22
  • @DevSolar: Ok, You're right. My poor template skill can not code The extra capability of SSTR("i = " << x); And I totally agree with your statement about fundamentalism ^^ You get a +1 from me. Greetings to your C64 ;) – neuro Jan 17 '11 at 09:52
  • @neuro: I wish I still had one. I'm going along quite well with VICE though. Oh, and I *do* still have an Amiga A600 in the basement. You want? ;-) – DevSolar Jan 17 '11 at 13:41
  • @DevSolar: Well thank you, but I still have an old A500 that probablty does not work anymore, but my old A1200 worked well some 5 years ago :) I just miss my old Sinclair ZX81. Sorry for your C64 ;) – neuro Jan 24 '11 at 15:59
  • @DevSolar boost::lexical_cast is faster: http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast/performance.html – Catskul Jun 03 '13 at 22:36
  • @Catskul: That might be. But there are places where Boost might not be an option. – DevSolar Jun 04 '13 at 05:44
3

You can use this function to convert int to std::string after including <sstream>:

#include <sstream>

string IntToString (int a)
{
    stringstream temp;
    temp<<a;
    return temp.str();
}
dodo
  • 33
  • 4
1

While std::to_string is a straightforward tool that should be kept in mind, starting with C++20, you may include <format>, which allows for more elaborates conversations from int to string:

#include <iostream>
#include <locale>
#include <format>

int main()
{
    using std::cout, std::endl;

    auto const n = 42;
    cout << std::format("{}", n) << endl;
    cout << std::format("{:d}", n) << endl;
    cout << std::format("{:#x}", n) << endl;
    cout << std::format("{:#o}", n) << endl;
    cout << std::format("{:#b}", n) << endl;
}

output:

42
42
0x2a
052
0b101010
Wolf
  • 9,679
  • 7
  • 62
  • 108
0

You might include the implementation of itoa in your project.
Here's itoa modified to work with std::string: http://www.strudel.org.uk/itoa/

ArtemGr
  • 11,684
  • 3
  • 52
  • 85
-3

Suppose I have integer = 0123456789101112. Now, this integer can be converted into a string by the stringstream class.

Here is the code in C++:

   #include <bits/stdc++.h>
   using namespace std;
   int main()
   {
      int n,i;
      string s;
      stringstream st;
      for(i=0;i<=12;i++)
      {
        st<<i;
      }
      s=st.str();
      cout<<s<<endl;
      return 0;

    }
Peter David Carter
  • 2,548
  • 8
  • 25
  • 44
Shawon
  • 21
  • 3
-3
#include <string>
#include <stdlib.h>

Here, is another easy way to convert int to string

int n = random(65,90);
std::string str1=(__String::createWithFormat("%c",n)->getCString());

you may visit this link for more methods https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/

kefir500
  • 4,184
  • 6
  • 42
  • 48