Amir Rachum
Amir Rachum

Reputation: 79695

Converting an int to std::string

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

Upvotes: 240

Views: 430349

Answers (12)

Wolf
Wolf

Reputation: 10238

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

Upvotes: 2

neuro
neuro

Reputation: 15200

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();
}

Upvotes: 39

dodo
dodo

Reputation: 43

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();
}

Upvotes: 4

Vipul Dungranee
Vipul Dungranee

Reputation: 1

#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/

Upvotes: -3

Shawon
Shawon

Reputation: 21

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;

    }

Upvotes: -3

user2622016
user2622016

Reputation: 6423

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.

Upvotes: 20

Yochai Timmer
Yochai Timmer

Reputation: 49261

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

int i = 3;
std::string str = std::to_string(i);

Upvotes: 489

Zac Howland
Zac Howland

Reputation: 15870

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

Upvotes: 15

ltjax
ltjax

Reputation: 16007

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:

Upvotes: 37

ArtemGr
ArtemGr

Reputation: 12567

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/

Upvotes: 0

DevSolar
DevSolar

Reputation: 70372

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;
}

Upvotes: 8

Benoit
Benoit

Reputation: 79235

#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());

Upvotes: 49

Related Questions