我试过这个例子:
/* 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
不存在)。
发布于 2012-03-11 21:12:58
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
除非您的编译器以某种方式为int
使用了超过32位的数组,否则所有可由int
表示的数字都可以放入12个字符的数组中,而不会溢出。当使用具有更大位数的数字时,例如大多数64位编译器的long
,您需要增加数组大小-对于64位类型,至少21个字符。
发布于 2012-03-12 10:09:32
制作自己的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()
函数。
发布于 2012-03-11 21:10:17
这是因为itoa
不是一个标准函数。请尝试使用snprintf
。
char str[LEN];
snprintf(str, LEN, "%d", 42);
https://stackoverflow.com/questions/9655202
复制相似问题