Alternative to itoa() for converting integer to string C++?
In C++11 you can use std::to_string
:
#include <string>
std::string s = std::to_string(5);
If you're working with prior to C++11, you could use C++ streams:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
Converting int to string in C
Use snprintf
, it is more portable than itoa
.
itoa is not part of standard C, nor is it part of standard C++; but, a lot of compilers and associated libraries support it.
Example of sprintf
char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);
Example of snprintf
char buffer[10];
int value = 234452;
snprintf(buffer, 10, "%d", value);
Both functions are similar to fprintf
, but output is written into an array rather than to a stream. The difference between sprintf
and snprintf
is that snprintf
guarantees no buffer overrun by writing up to a maximum number of characters that can be stored in the buffer
.
Want to Convert Integer to String without itoa function
I found solution regarding this..
I am Happy to and i want which i expected.
#include <string.h>
#include <stdlib.h>
char *i_to_a(int num);
int main()
{
char *str = i_to_a(4567);
printf("%s",str);
free(str);
str = NULL;
return 0;
}
int no_of_digits(int num)
{
int digit_count = 0;
while(num > 0)
{
digit_count++;
num /= 10;
}
return digit_count;
}
char *i_to_a(int num)
{
char *str;
int digit_count = 0;
if(num < 0)
{
num = -1*num;
digit_count++;
}
digit_count += no_of_digits(num);
str = malloc(sizeof(char)*(digit_count+1));
str[digit_count] = '\0';
while(num > 0)
{
str[digit_count-1] = num%10 + '0';
num = num/10;
digit_count--;
}
if(digit_count == 1)
str[0] = '-';
return str;
}
C++ standard alternative to itoa() to convert int to base 10 char*
I recommend using roybatty's answer, but I think sprintf should work too. I think when you used it you forgot the format string. It should be:
char buf[16];
std::snprintf(buf, sizeof(buf), "%d", integer);
Easiest way to convert int to string in C++
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)
Converting integer to string in C without sprintf
You can use itoa where available. If it is not available on your platform, the following implementation may be of interest:
https://web.archive.org/web/20130722203238/https://www.student.cs.uwaterloo.ca/~cs350/common/os161-src-html/atoi_8c-source.html
Usage:
char *numberAsString = itoa(integerValue);
UPDATE
Based on the R..'s comments, it may be worth modifying an existing itoa implementation to accept a result buffer from the caller, rather than having itoa allocate and return a buffer.
Such an implementation should accept both a buffer and the length of the buffer, taking care not to write past the end of the caller-provided buffer.
Purpose of char a[0] in converting integer to string using itoa()
Since itoa
function is non-standard, this is a discussion of a popular signature itoa(int, char*, int)
.
Second parameter represents a buffer into which a null-terminated string representing the value is copied. It must provide enough space for the entire string: in your case, that is "123"
, which takes four characters. Your code passes a[]
as the buffer, but the size of a[]
is insufficient to accommodate the entire "123"
string. Hence, the call causes undefined behavior.
You need to make a
large enough to fit the destination string. Passing a buffer of size 12 is sufficient to accommodate the longest decimal number that can be produced by itoa
on a 32-bit system (i.e. -2147483648
). Replace char a[0]
with char a[12]
in the declaration.
converting integer to string C++
Besides I would prefer if I could convert the same int to char array.
char *charPtr = new char[ s.length() + 1 ] ; // s is the string in the snippet posted
strcpy( charPtr, s.c_str() ) ;
// .......
delete[] charPtr ; // Should do this, else memory leak.
integer to string conversion using itoa()
You have to use
char string[5];
int integer= 10;
snprintf(string, 5,"%d",integer);
Because itoa
is not part of the standard function which is supported by some compilers..
Related Topics
Unmangling the Result of Std::Type_Info::Name
What Is a Converting Constructor in C++ ? What Is It For
Gcc Optimization Flag -O3 Makes Code Slower Than -O2
Why Does C++ Require a Cast For Malloc() But C Doesn'T
Can Main Function Call Itself in C++
Are the Days of Passing Const Std::String & as a Parameter Over
Difference in Make_Shared and Normal Shared_Ptr in C++
Namespace + Functions Versus Static Methods on a Class
Static Constant String (Class Member)
Do You Use Null or 0 (Zero) For Pointers in C++
How to Write Iso C++ Standard Conformant Custom New and Delete Operators
C++ "Virtual" Keyword For Functions in Derived Classes. Is It Necessary
What Happens If You Call Erase() on a Map Element While Iterating from Begin to End
How to Detect Whether There Is a Specific Member Variable in Class
How Does the Import Library Work - Details
Function Parameter Evaluation Order
Setup Opencv-2.3 For Visual Studio 2010
Should Operator≪≪ Be Implemented as a Friend or as a Member Function