Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

c - 如何在C中将整数转换为字符串? [重复](How to convert integer to string in C? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

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
",buffer);
    itoa (i,buffer,16);
    printf ("hexadecimal: %s
",buffer);
    itoa (i,buffer,2);
    printf ("binary: %s
",buffer);
    return 0;
}

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

(但那里的例子不起作用(它表示itoa不存在的功能)。)

  ask by janko-m translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use sprintf() :

(使用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 .

(所有可由int表示的数字都将适合12-char数组而不会溢出,除非您的编译器以某种方式使用超过32位的int 。)

When using numbers with greater bitsize, eg long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

(当使用具有更大位数的数字时,例如对于大多数64位编译器来说long ,则需要增加数组大小 - 对于64位类型,至少需要21个字符。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...