这个问题在这里已经有了答案:How to convert an int to string in C? (11 个回答) 9 年前关闭。
我试过这个例子:
/* 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;
}
但那里的例子不起作用(它说函数 itoa
不存在)。
使用 sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
int
可以表示的所有数字都将适合 12 字符数组而不会溢出,除非您的编译器以某种方式使用超过 32 位的 int
。当使用具有更大位大小的数字时,例如 long
对于大多数 64 位编译器,您需要增加数组大小 — 对于 64 位类型,至少 21 个字符。
制作自己的 itoa
也很容易,试试这个:
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;
}
或使用标准的 sprintf()
函数。
i *= -1
行,它会在 i = INT_MIN
时失败。
while
测试循环开始前的条件,do while
测试循环开始后的条件。
那是因为 itoa
不是标准函数。请改用 snprintf
。
char str[LEN];
snprintf(str, LEN, "%d", 42);
(CHAR_BIT * sizeof(int) - 1) / 3 + 2
作为 caf mentioned。
- 1
。
sprintf
在这里更详细地讨论:stackoverflow.com/questions/8232634/simple-use-of-sprintf-cstr
会有多大的情况。 (例如多字节字符、表示无限制计数器的数字等)。