197

I tried this 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;
}

but the example there doesn't work (it says the function itoa doesn't exist).

Janko
  • 8,985
  • 7
  • 34
  • 51
  • 3
    You should give more information, like the *exact* error message, what compiler you're using, and what OS. – Gabe Mar 11 '12 at 13:13
  • [my-itoa](http://code.google.com/p/my-itoa/) was already suggested somewhere else on SO. – menjaraz Mar 11 '12 at 13:46

3 Answers3

303

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

qwertz
  • 14,614
  • 10
  • 34
  • 46
  • 1
    I tried running this program, and I got a runtime error. How can I get it to work properly? http://ideone.com/Xl21B4 – Anderson Green Mar 06 '13 at 02:56
  • @AndersonGreen The code here is correct. You typed it incorrectly. The error message tells you where. – nschum Mar 08 '13 at 09:31
  • `sprintf` is discussed here in more detail: http://stackoverflow.com/questions/8232634/simple-use-of-sprintf-c – Anderson Green Mar 08 '13 at 21:07
  • 11
    Often it's better to use snprintf() to cover situations where you don't know how big `str` is going to be. (eg multi-byte characters, numbers that represent counters without a limit, etc). – gone Apr 23 '14 at 09:21
60

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

bhuwansahni
  • 1,834
  • 1
  • 14
  • 20
50

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);
cnicutar
  • 178,505
  • 25
  • 365
  • 392