How to convert integer to string in C?

ID : 20114

viewed : 51

Tags : cstringintegertype-conversionc

Top 5 Answer for How to convert integer to string in C?

vote vote

91

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.

vote vote

83

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.

vote vote

76

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

char str[LEN]; snprintf(str, LEN, "%d", 42); 
vote vote

69

vote vote

54

if you use Azure Devops:

  1. Under your project repo, select Branches.

  2. On the Branches page, select More options next to the new default branch you want, and choose Set as default branch.

enter image description here

  1. After you set the new default branch, you can delete the previous default if you want.

Top 3 video Explaining How to convert integer to string in C?

Related QUESTION?