As itoa()
is indeed non-standard, as mentioned by several helpful commenters, it is best to use sprintf(target_string,"%d",source_int)
or (better yet, because it's safe from buffer overflows) snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int)
. I know it's not quite as concise or cool as itoa()
, but at least you can Write Once, Run Everywhere (tm) ;-)
sprintf(target_string,"%d",source_int)
snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int)
You are correct in stating that the default gcc libc
does not include itoa()
, like several other platforms, due to it not technically being a part of the standard. See here for a little more info. Note that you have to
#include <stdlib.h>
Of course you already know this, because you wanted to use itoa()
on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:
Example
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}
Output:
Enter a number: 1750 decimal: 1750 hexadecimal: 6d6 binary: 11011010110