How to convert int to string in C++?
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.
How does option 1 even work for you at all? It’s my understanding that itoa() takes three parameters.
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: Once you start worrying about which is faster, you’ll want to look at stackoverflow.com/questions/4351371/…
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().
31 Answers 31
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 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:
Note: see [string.conversions] (21.5 in n3242)
@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++
@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);
C++20: std::format would be the idiomatic way now.
Picking up a discussion with @v.oddou a couple of years later, C++17 has delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro ugliness.
// variadic template template < typename. Args >std::string sstr( Args &&. args ) < std::ostringstream sstr; // fold expression ( sstr
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 ) );
Since "converting . to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:
#include #define SSTR( x ) static_cast< std::ostringstream & >( \ ( std::ostringstream()
Usage is as easy as could be:
int i = 42; std::string s = SSTR( "i is: "
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.
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: The link in my answer leads to a detailed description of each part of the construct. While we created a ostringstream , we called operator
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: 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: Look at what I found among the things C++17 brought us. 🙂 I hope you like the updated answer.
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(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).
Convert Int to String in C
Strings data types are everywhere in modern programming, from low-level programming languages to high-level languages that make a great effort to abstract the fundamental concepts. Therefore, you will find yourself working with strings in any programming language more times than not.
For that purpose, we will discuss quick and very beginner-friendly methods of converting an integer into a string in the C programming language.
Method 1 – Convert Int to String Using the Sprintf Function
The Sprintf function is one of the functions you can use to convert an integer value into a string. As the name suggests, the function will take any value and print it into a string.
It is very similar to the printf function. But instead of printing the value into the standard out, the function returns a formatted string which we can store in a variable and use later.
The function syntax is as shown below:
The function accepts three main parameters:
- str – this specifies a pointer to a char data type.
- format – the format parameter allows you to specify the type of output with a placeholder.
- args – this parameter specifies the integer values in which to convert into a string.
You will notice that the function returns an int type. This is because it returns a formatted string which is discarded, and a value of -1 if an error occurs.
Let us see this function in action.
int main ( ) {
int var = 100 ;
char int_str [ 20 ] ;
sprintf ( int_str , "%d" , var ) ;
printf ( "Var: %s \n " , int_str ) ;
return 0 ;
}
In the code above, we start by importing the necessary header files. For the sprint() function, we require the standard input and output header file only.
We then open the main function and declare two variables. The first is the integer value that we wish to convert to a string.
The next variable is the character array that we will use to store the string value once we convert the int into a string.
We then use the sprint function and pass the char type, the format, and the int as the parameters.
Finally, we can print the resulting string using the printf function. The resulting output is a shown:
Method 2 – Convert Int to String With itoa() Function (non-standard)
There is another non-standard function in C that you can use to convert an int to a string. It is a simple type-casting function. It first appeared in the C Programming Language book.
However, as the book states, this function is non-standard and does not handle negative integers very well.
Since it is non-standard, attempting to compile the function will heavily depend on your OS and if the function is available.
However, we are developers, and experimenting is in our nature.
The following syntax shows how the itoa() function works.
The function takes three main parameters:
- num – this parameter refers to the int value that you wish to convert to a string.
- buffer – the buffer parameter is a pointer to a char data type to hold the converted string.
- base – refers to the conversion base.
The function then returns a string of the specified integer.
The code below illustrates how to use the itoa() function to convert an int to a string.
int var = 100 ;
char int_string [ 20 ] ;
itoa ( var , int_string , 10 ) ;
printf ( "Var: %s \n " , int_string ) ;
Here, we specify the conversion of the int to base 10.
Closing
In this article, we covered two main methods of converting an Int to a string in C. It is good to stick to the Sprintf function as it’s a standard function and can be exported across systems.
Thanks for reading, and Happy coding!!
About the author
John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list
std::to_string (3) - Linux Manuals
Defined in header
std::string to_string( int value ); (1) (since C++11)
std::string to_string( long value ); (2) (since C++11)
std::string to_string( long long value ); (3) (since C++11)
std::string to_string( unsigned value ); (4) (since C++11)
std::string to_string( unsigned long value ); (5) (since C++11)
std::string to_string( unsigned long long value ); (6) (since C++11)
std::string to_string( float value ); (7) (since C++11)
std::string to_string( double value ); (8) (since C++11)
std::string to_string( long double value ); (9) (since C++11)
Converts a numeric value to std::string.
1) 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.
2) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%ld", value) would produce for sufficiently large buf.
3) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%lld", value) would produce for sufficiently large buf.
4) Converts an unsigned decimal integer to a string with the same content as what std::sprintf(buf, "%u", value) would produce for sufficiently large buf.
5) Converts an unsigned decimal integer to a string with the same content as what std::sprintf(buf, "%lu", value) would produce for sufficiently large buf.
6) Converts an unsigned decimal integer to a string with the same content as what std::sprintf(buf, "%llu", value) would produce for sufficiently large buf.
7,8) Converts a floating point value to a string with the same content as what std::sprintf(buf, "%f", value) would produce for sufficiently large buf.
9) Converts a floating point value to a string with the same content as what std::sprintf(buf, "%Lf", value) would produce for sufficiently large buf.