如何在C中将整数转换为字符串?

我试过这个例子:


/* 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不存在)。


暮色呼如
浏览 502回答 3
3回答

心有法竹

自己制作itoa也很容易,请尝试以下操作:char* itoa(int i, char b[]){&nbsp; &nbsp; char const digit[] = "0123456789";&nbsp; &nbsp; char* p = b;&nbsp; &nbsp; if(i<0){&nbsp; &nbsp; &nbsp; &nbsp; *p++ = '-';&nbsp; &nbsp; &nbsp; &nbsp; i *= -1;&nbsp; &nbsp; }&nbsp; &nbsp; int shifter = i;&nbsp; &nbsp; do{ //Move to where representation ends&nbsp; &nbsp; &nbsp; &nbsp; ++p;&nbsp; &nbsp; &nbsp; &nbsp; shifter = shifter/10;&nbsp; &nbsp; }while(shifter);&nbsp; &nbsp; *p = '\0';&nbsp; &nbsp; do{ //Move back, inserting digits as u go&nbsp; &nbsp; &nbsp; &nbsp; *--p = digit[i%10];&nbsp; &nbsp; &nbsp; &nbsp; i = i/10;&nbsp; &nbsp; }while(i);&nbsp; &nbsp; return b;}或使用标准sprintf()功能。

开满天机

用途sprintf():int someInt = 368;char str[12];sprintf(str, "%d", someInt);可以用表示的所有数字都int将适合12个字符的数组,且不会溢出,除非您的编译器以某种方式使用了32位以上的int。当使用更大位数的数字时,例如long,在大多数64位编译器中,您需要增加数组大小-对于64位类型,至少要增加21个字符。
打开App,查看更多内容
随时随地看视频慕课网APP