By Nemo


2011-04-08 04:19:41 8 Comments

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

27 comments

@Tayyab Mazhar 2018-06-05 08:02:25

Use:

#include<iostream>
#include<string>

std::string intToString(int num);

int main()
{
    int integer = 4782151;

    std::string integerAsStr = intToString(integer);

    std::cout << "integer = " << integer << std::endl;
    std::cout << "integerAsStr = " << integerAsStr << std::endl;

    return 0;
}

std::string intToString(int num)
{
    std::string numAsStr;

    while (num)
    {
        char toInsert = (num % 10) + 48;
        numAsStr.insert(0, 1, toInsert);

        num /= 10;
    }
    return numAsStr;
}

@Toby Speight 2019-12-03 09:17:56

Completely fails for n≤0

@Alek 2016-11-25 07:36:24

EDITED. If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is the example for little-endian architectures (all x86, x86_64 and others):

If you are converting a two-digit number:

int32_t s = 0x3030 | (n/10) | (n%10) << 8;

If you are converting a three-digit number:

int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;

If you are converting a four-digit number:

int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;

And so on up to seven-digit numbers. In this example n is a given integer. After conversion it's string representation can be accessed as (char*)&s:

std::cout << (char*)&s << std::endl;

NOTE: If you need it on big-endian byte order, though I did not tested it, but here is an example: for three-digit number it is int32_t s = 0x00303030 | (n/100)<< 24 | (n/10%10)<<16 | (n%10)<<8; for four-digit numbers (64 bit arch): int64_t s = 0x0000000030303030 | (n/1000)<<56 | (n/100%10)<<48 | (n/10%10)<<40 | (n%10)<<32; I think it should work.

@shjeff 2019-01-10 15:31:54

What about byte-order?

@dgnuff 2019-11-15 20:15:01

Isn't this undefined behavior due to pointer aliasing?

@Alek 2019-11-16 12:18:19

@shjeff thanks for the comment, I added a note on endianness to the answer.

@Alek 2019-11-16 12:23:16

@dgnuff thanks for pointing this out, although I've had no problems with this, you are right. I slightly modified the answer so that it complies Strict Aliasing Rules, thanks.

@YesThatIsMyName 2017-08-18 12:47:29

Using stringstream for number conversion is dangerous!

See http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ where it tells that operator<< inserts formatted output.

Depending on your current locale an integer greater than 3 digits, could convert to a string of 4 digits, adding an extra thousands separator.

E.g., int = 1000 could be convertet to a string 1.001. This could make comparison operations not work at all.

So I would strongly recommend using the std::to_string way. It is easier and does what you expect.

Updated (see comments below):

C++17 provides std::to_chars as a higher-performance locale-independent alternative

@Bert Bril 2017-10-24 22:05:46

I agree that this is a serious problem if you need to exchange data. Unfortunately, also std::to_string uses the current locale (see en.cppreference.com/w/cpp/string/basic_string/to_string , the 'Notes' section). Almost all standard tools (from stringstreams to sprintf, but also sscanf etc) are using the current locale. I wasn't aware of this until recently when it hit me hard. Currently using home-grown stuff, not hard to make.

@YesThatIsMyName 2018-01-10 12:01:40

In the link above it is also statet that C++17 provides std::to_chars as a higher-performance locale-independent alternative.

@Bert Bril 2018-01-12 21:39:51

Unfortunately, I am stuck with C++11 for the coming year(s) (quite an improvement already, luckily).

@gast128 2019-10-10 10:37:03

from_chars and to_chars would be perfect but unfortunately they didn't offer a wchar_t variant.

@Kamrujjaman Joy 2018-07-26 13:46:54

C++11 introduced std::to_string() for numeric types:

int n = 123; // Input, signed/unsigned short/int/long/long long/float/double
std::string str = std::to_string(n); // Output, std::string

@anothernode 2018-07-26 14:21:23

Hi! Could you add an explanation on why and how this provides an answer to the question?

@Tur1ng 2014-02-05 16:25:11

If you're using MFC, you can use CString:

int a = 10;
CString strA;
strA.Format("%d", a);

@JonnyJD 2014-02-05 16:57:02

You should note that this is a Microsoft-only extension: msdn.microsoft.com/en-us/library/ms174288.aspx

@Nick 2016-02-24 13:46:19

I love the idea of CString::Format(). Unfortunate it it non portable MS only.

@Tur1ng 2019-06-25 18:14:45

I have updated my answer to include the information from your comment @JonnyJD, since I keep getting downvoted for it 5 years later..

@Gonçalo Garrido 2019-05-14 11:12:34

This worked for me -

My code:

#include <iostream>
using namespace std;

int main()
{
    int n = 32;
    string s = to_string(n);
    cout << "string: " + s  << endl;
    return 0;
}

@Peter Mortensen 2019-05-31 12:22:12

Essentially using what? stringstream?

@Vladislav Toncharov 2019-07-03 11:15:15

@PeterMortensen Look carefully, it's std::to_string()

@rashedcs 2018-09-17 13:37:26

I think using stringstream is pretty easy:

 string toString(int n)
 {
     stringstream ss(n);
     ss << n;
     return ss.str();
 }

 int main()
 {
    int n;
    cin >> n;
    cout << toString(n) << endl;
    return 0;
 }

@Vladislav Toncharov 2019-07-03 10:58:26

This was mentioned in the question, and unfortunately is quite slow.

@Natesh bhat 2018-02-07 16:10:56

Here's another easy way to do

char str[100];
sprintf(str, "%d", 101);
string s = str;

sprintf is a well-known one to insert any data into a string of the required format.

You can convert a char * array to a string as shown in the third line.

@AdmiralSmith 2016-10-09 19:18:05

You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.

  • You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.

    • If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
      keep doing it until no more numbers in position 100,000. Drop another power of ten.

    • If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
      keep doing it until no more numbers in position 10,000.

  • Drop another power of ten

  • Repeat the pattern

I know 950 is too small to use as an example, but I hope you get the idea.

@Abdullah Abdelmonem 2015-12-16 21:10:45

string number_to_string(int x) {

    if (!x)
        return "0";

    string s, s2;
    while(x) {
        s.push_back(x%10 + '0');
        x /= 10;
    }
    reverse(s.begin(), s.end());
    return s;
}

@Toby Speight 2019-12-03 09:12:03

Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.

@Toby Speight 2019-12-03 09:18:26

Completely fails for n≤0

@Aksen P 2019-12-03 09:29:06

Add comments, explain your answer, read how to answer.

@vitaut 2014-05-25 13:42:10

You can use std::to_string available in C++11 as suggested by Matthieu M.:

std::to_string(42);

Or, if performance is critical (for example, if you do lots of conversions), you can use fmt::format_int from the {fmt} library to convert an integer to std::string:

fmt::format_int(42).str();

Or a C string:

fmt::format_int f(42);
f.c_str();

The latter doesn't do any dynamic memory allocations and is more than 10 times faster than std::to_string on Boost Karma benchmarks. See Fast integer to string conversion in C++ for more details.

Note that both are thread-safe.

Unlike std::to_string, fmt::format_int doesn't require C++11 and works with any C++ compiler.

Disclaimer: I'm the author of the {fmt} library.

@Soren 2014-06-16 22:17:00

I was curious about the claim of not having any dynamic memory allocation while remain threadsafe (re-entrant), so I read your code -- the c_str() returns a pointer to a buffer declared inside the fmt::FormatInt class -- so the pointer returned will be invalid at the semicolon -- see also stackoverflow.com/questions/4214153/lifetime-of-temporaries

@vitaut 2014-06-16 23:40:52

Yes, the same behavior as with std::string::c_str() (thus the naming). If you want to use it outside of the full expression construct an object FormatInt f(42); Then you can use f.c_str() without a danger of it being destroyed.

@user8951490 2018-02-09 07:25:32

I get something weird when I try to convert from int to string using std::to_string(num). If I store the result in a variable and try to Access it like stringNum[1] or stringNum[n] as n increases, I get garbage.

@J_C 2014-01-18 19:59:51

I use:

int myint = 0;
long double myLD = 0.0;

string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();

It works on my Windows and Linux g++ compilers.

@user2287915 2013-04-16 19:37:04

It would be easier using stringstreams:

#include <sstream>

int x = 42;          // The integer
string str;          // The string
ostringstream temp;  // 'temp' as in temporary
temp << x;
str = temp.str();    // str is 'temp' as string

Or make a function:

#include <sstream>

string IntToString(int a)
{
    ostringstream temp;
    temp << a;
    return temp.str();
}

@user1363411 2013-02-21 10:18:15

namespace std
{
    inline string to_string(int _Val)
    {   // Convert long long to string
        char _Buf[2 * _MAX_INT_DIG];
        snprintf(_Buf, "%d", _Val);
        return (string(_Buf));
    }
}

You can now use to_string(5).

@iFreilicht 2014-11-19 14:57:57

While this solution works, it is highly discouraged! Names starting with underscore and a capital letter are reserved for the compiler, you shouldn't ever use them. Injecting functions into the std namespace is not something you should ever do, either. Also, it doesn't seem like _MAX_INT_DIG is a standard macro, so if it is defined wrongly, this code has the great potential of inducing undefined behaviour. -1

@paulm 2015-03-25 16:27:14

What is _MAX_INT_DIG and why is it doubled?

@user2047065 2013-02-06 13:40:56

char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);

@paulm 2015-03-25 16:27:41

leaks memory, -1 from me

@Vladislav Toncharov 2019-07-03 10:49:03

This smells like buffer overrun.

@Rasoul 2012-11-29 22:46:12

I usually use the following method:

#include <sstream>

template <typename T>
  std::string NumberToString ( T Number )
  {
     std::ostringstream ss;
     ss << Number;
     return ss.str();
  }

It is described in details here.

@lifebalance 2015-06-09 02:48:15

Before using ss, you need to ss.clear() it. I've seen unexpected results without this initialization.

@Rasoul 2015-06-11 08:23:56

@lifebalance: I have never seen such behavior.

@Remy Lebeau 2015-08-05 04:00:21

@lifebalance: You do not need to clear() a newly created ostringstream object. clear() resets the error/eof flags, and there has not been any error/eof condition generated yet.

@Killzone Kid 2017-11-05 23:00:16

@Rasoul NumberToString(23213.123) produces 23213.1 while std::to_string(23213.123) produces 23213.123000 What happens there?

@phorgan1 2018-11-23 02:04:05

I wouldn't normally write a function for three lines, but it does make it self documenting via the name. Clarity vs self documenting -- those shouldn't conflict, right?

@xryl669 2019-06-14 14:04:31

@KillzoneKid This is because std' ostream are stateful (this means that any previous state change is kept, like the number of decimal digit) while this method starts with a default state.

@user10133158 2019-01-04 11:21:05

C++17 provides std::to_chars as a higher-performance locale-independent alternative.

@DevSolar 2011-04-08 04:23:10

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

@Mathew 2014-10-21 02:38:35

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?

@DevSolar 2014-10-21 06:59:31

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

@Mathew 2014-10-21 14:55:19

@DevSolar thanks for the details! The reason clang throws a compile time error is because llvm purposefully omits standard RTTI for space/time savings. There are alternatives available for clang, but I was still curious why the cast was needed. I am just guessing here, but I imagine clang is allowing me to make an implicit cast back to ostringstream and that is why I am not getting a compiler error for dropping the dynamic_cast.

@chappjc 2015-01-23 22:16:21

The usage seems to be missing i, unlike on your wiki.

@v.oddou 2015-06-18 03:30:48

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 2015-06-18 03:36:03

3. crazy parameter interface. the usage you demonstrate violates POLA very bad. for this feature, what we expect is to pass a value not an expression.

@DevSolar 2015-06-18 08:45:47

@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".

@v.oddou 2015-06-18 09:01:25

point 1 is invalid for this macro, indeed; but what I stated is a general point for all macros, I placed the concern at the point of view of the client, that means, for a reader at the usage site. Any sighting of any macro raises the 2 concerns I listed (to a reader/reviewer). I didn't know this SSTR was a semi-standard, I never encountered it. And I am glad, lol ;)

@DevSolar 2018-05-13 20:57:29

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

@Matthieu M. 2011-04-08 06:13:52

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)

@Ben 2012-11-02 03:02:19

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

@Thomas M. DuBuisson 2012-11-29 23:12:13

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

@Mooing Duck 2013-05-31 21:34:33

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

@user2643530 2013-09-26 13:51:33

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

@Matthieu M. 2013-09-26 14:31:45

@Flying: VS2010 is sorely lacking in C++11 support as far as I know; however since I do not use it myself, I cannot check.

@Zac 2013-12-06 14:50:12

@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);

@Ming 2014-08-12 05:42:17

NOTE: It won't work in NDK. to_string is not implemented in NDK.

@Hosi 2015-04-12 05:28:01

And check this out: zverovich.net/2013/09/07/… if you have any speed concern.

@noɥʇʎԀʎzɐɹƆ 2016-08-08 18:32:09

this converts a string to an integer, not a integer to string.

@Matthieu M. 2016-08-09 01:57:55

@uoɥʇʎPʎzɐɹC: I encourage you to look at the code sample more closely. 42 (a literal) is being converted into s (a std::string).

@Chan Kim 2016-08-16 07:59:14

in my case, it gives me aa.cpp:9: error: 'to_string' is not a member of 'std' error and adding -std=c++11 option gives me cc1plus: error: unrecognized command line option "-std=c++11" error. gcc version4.4.7.

@Matthieu M. 2016-08-16 14:38:13

@ChanKim: Your compiler (gcc 4.4.7) is telling you that it is not suitable for C++11; as a result the std::to_string function is unavailable to you. A number of solutions below (such as using std::ostringstream) are suitable for C++03 (or C++98), though quite slower; or you can simply write the function yourself (not that hard for integrals, though beware of overflows).

@Chan Kim 2016-08-16 14:49:12

@MatthieuM. I see. BTW, we know if it is just for printing, we can use std::cout << that'll convert integer for printing. I'd use ostringstream.str().

@user6244076 2017-01-11 08:07:32

I use MinGW-w64 and I don't have this problem, in fact, it doesn't use C++98 only if I tell it to.

@Matthieu M. 2017-01-11 08:09:43

@theo2003: All modern compilers will default to C++11 or later by now, so unless you are stuck with an old compiler (still happen in some work places unfortunately), then std::to_string should be available to you by default indeed.

@Pryftan 2018-04-04 02:05:23

Something tells me that it's not like atoi() but strtol(). Some might point out that long != int but as the man page of atoi() says (verbatim): The behavior is the same as strtol(nptr, NULL, 10); except that atoi() does not detect errors. - and that's what makes me think of it being not atoi(). Of course itoa() isn't defined in the C standard so I can't comment on that one.

@phorgan1 2018-11-23 02:02:03

std::to_string(int val) is listed in 21.5 numeric conversion in the C++11 spec and conforms to the current locale

@AndreyS Scherbakov 2018-02-03 09:17:31

It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way

#include <string>
#include <sstream>

struct strmake {
    std::stringstream s;
    template <typename T> strmake& operator << (const T& x) {
        s << x; return *this;
    }   
    operator std::string() {return s.str();}
};

Now you may append whatever you want (provided that an operator << (std::ostream& ..) is defined for it) to strmake() and use it in place of an std::string.

Example:

#include <iostream>

int main() {
    std::string x =
      strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
    std::cout << x << std::endl;
}

@maverick9888 2016-04-14 09:10:27

Use:

#define convertToString(x) #x

int main()
{
    convertToString(42); // Returns const char* equivalent of 42
}

@Wolf 2016-05-31 12:48:26

Works only with literal numbers, doesn't evaluate variable content, though useful sometimes.

@maverick9888 2016-10-03 04:26:08

Right. But definitely handy at time

@Ing. Gerardo Sánchez 2017-11-03 01:48:49

Only works at compile time with literal constants numbers, i think the OP asks for a dynamic conversion, using variable integers

@Joshua Detwiler 2017-06-20 14:48:14

For C++98, there's a few options:

boost/lexical_cast

Boost is not a part of the C++ library, but contains many useful library extensions.

The lexical_cast function template offers a convenient and consistent form for supporting common conversions to and from arbitrary types when they are represented as text.
-- Boost's Documentation

#include "boost/lexical_cast.hpp"
#include <string>

int main() {
    int x = 5;
    std::string x_str = boost::lexical_cast<std::string>(x);
    return 0;
}

As for runtime, the lexical_cast operation takes about 80 microseconds (on my machine) on the first conversion, and then speeds up considerably afterwards if done redundantly.


itoa

This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
-- cplusplus.com

This means that gcc/g++ cannot compile code using itoa.

#include <stdlib.h>

int main() {
    int x = 5;
    char * x_str = new char[2];
    x_str = itoa(x, x_str, 10); // base 10
    return 0;
}

No runtime to report. I don't have Visual Studio installed, which is reportedly able to compile itoa.


sprintf

sprintf is a C standard library function that works on C strings, and is a perfectly valid alternative.

Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.
-- cplusplus.com

#include <stdio.h>

int main() {
    int x = 5;
    char * x_str = new char[2];
    int chars_written = sprintf(x_str, "%d", x);
    return 0;
}

The stdio.h header may not be necessary. As for runtime, the sprintf operation takes about 40 microseconds (on my machine) on the first conversion, and then speeds up considerably afterwards if done redundantly.


stringstream

This is the C++ library's main way of converting integers to strings, and vice versa. There are similar sister functions to stringstream that further limit the intended use of the stream, such as ostringstream. Using ostringstream specifically tells the reader of your code that you only intend to use the << operator, essentially. This function is all that's particularly necessary to convert an integer to a string. See this question for a more elaborate discussion.

#include <sstream>
#include <string>

int main() {
    int x = 5;
    std::ostringstream stream;
    stream << x;
    std::string x_str = stream.str();
    return 0;
}

As for runtime, the ostringstream operation takes about 71 microseconds (on my machine), and then speeds up considerably afterwards if done redundantly, but not by as much as the previous functions.


Of course there are other options, and you can even wrap one of these into your own function, but this offers an analytical look at some of the popular ones.

@A. B 2018-04-19 00:47:17

Thanks for looking after us (C++98 users)

@Vladislav Toncharov 2019-07-03 11:16:57

@A.B I can't beleive there're still any C++98 users left.

@Joshua Detwiler 2019-07-31 16:58:46

@VladislavToncharov When your job is solely to support legacy equipment and code, you muck in the old stuff using fresher industry standards. A summer ago, I was writing code in Python 2.3.

@Vladislav Toncharov 2019-08-01 14:44:17

@JoshuaDetwiler Oh, forgot about that, sorry.

@Jerry Coffin 2011-04-08 04:23:22

Probably the most common easy way wraps essentially your second choice into a template 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).

As of 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 = 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.

@Jason R. Mick 2013-03-21 14:15:55

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

@Alex 2013-06-21 08:16:02

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

@Alex 2013-05-31 21:32:41

First include:

#include <string>
#include <sstream>

Second add the method:

template <typename T>
string NumberToString(T pNumber)
{
 ostringstream oOStrStream;
 oOStrStream << pNumber;
 return oOStrStream.str();
}

Use the method like this:

NumberToString(69);

or

int x = 69;
string vStr = NumberToString(x) + " Hello word!."

@Throwback1986 2011-04-08 04:23:31

sprintf() is pretty good for format conversion. You can then assign the resulting C string to the C++ string as you did in 1.

@Throwback1986 2011-04-08 12:42:58

Heh, yes. However, I usually rely on snprintf() and friends for anything of consequence when handling C strings.

@user1095108 2013-09-25 07:07:17

@MatthieuM. You're uninformed. You don't need to hope, at least for sprintf variants, as they return the necessary size of a buffer.

@Matthieu M. 2013-09-25 07:46:24

@user1095108: I am well informed, unfortunately. sprintf returns the number of characters written to the buffer (or a negative number if it failed). Note that unlike snprintf it has no idea how large said buffer is, and may overwrite past the end.

@user1095108 2013-09-25 08:02:48

@MatthieuM. Your comment proves further, that you are not. If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. So you call it with a NULL and zero size to get the necessary buffer size.

@Matthieu M. 2013-09-25 09:37:04

@user1095108: I think you are mistaking snprintf (note the SNP prefix) and sprintf (note the SP prefix). You pass the size to the former, and it takes care not to overflow, however the latter knows not the size of the buffer and thus may overflow.

@user1095108 2013-09-25 09:40:38

The idea is to call a snprintf variant first and a sprintf variant after that. As the buffer size is known by then, calling sprintf becomes entirely safe.

@mabraham 2013-10-02 14:24:51

@user1095108 why call twice? If snprintf is called with a sufficient buffer, then there is no need for a second call unless you need to conserve the memory (and then strcpy is faster). If snprintf is not called with a sufficient buffer, a second call to either sprintf or snprintf is still not sure to work.

@user1095108 2013-10-02 20:52:47

@mabraham Interesting idea, call first with a "guess" buffer, then a second time, if the first call fails. But otherwise, what you write here is not true. You call for the first time exactly so that you find out what size the buffer has to be. After you find out the second call must succeed, if the snprintf implementation is written correctly.

@mabraham 2013-10-05 08:02:31

@user1095108 Ah, yes. If the first buffer to snprintf is insufficient, the return value tells you what would be sufficient. I would still use snprintf for the second call, because relying on the implementations of sprintf and snprintf to match is unnecessarily dangerous.

@Kevin 2011-04-08 04:26:01

If you have Boost installed (which you should):

#include <boost/lexical_cast.hpp>

int num = 4;
std::string str = boost::lexical_cast<std::string>(num);

@Werner Erasmus 2013-08-28 18:47:10

Agreed on boost installation. I think that more than often one would format the string. For this purpose I prefer boost::format e.g format("%02d", number ).str()

@Mehrdad 2011-04-08 04:22:15

Not that I know of, in pure C++. But a little modification of what you mentioned

string s = string(itoa(a));

should work, and it's pretty short.

@cartoonist 2012-11-15 11:25:37

itoa() is not a standard function!

@Mehrdad 2012-11-15 15:35:43

@cartoonist: Then what is it?

@cartoonist 2012-11-15 20:49:38

This function is not defined in ANSI-C and C++. So it's not supported by some compiler such as g++.

Related Questions

Sponsored Content

25 Answered Questions

[SOLVED] How do I parse a string to a float or int?

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

23 Answered Questions

[SOLVED] What is the "-->" operator in C++?

42 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

59 Answered Questions

[SOLVED] How to replace all occurrences of a string?

65 Answered Questions

[SOLVED] What is the difference between String and string in C#?

3 Answered Questions

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2144235 View
  • 2902 Score
  • 76 Answer
  • Tags:   c++ string split

1 Answered Questions

[SOLVED] The Definitive C++ Book Guide and List

  • 2008-12-23 05:23:56
  • grepsedawk
  • 2249646 View
  • 4246 Score
  • 1 Answer
  • Tags:   c++ c++-faq

3 Answered Questions

[SOLVED] Best way to convert string to bytes in Python 3?

Sponsored Content