如何在C中将整数转换为字符串? [英] How to convert integer to string in C?
本文介绍了如何在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
",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s
",buffer);
itoa (i,buffer,2);
printf ("binary: %s
",buffer);
return 0;
}
但是那里的例子不起作用(它说函数 itoa
不存在).
but the example there doesn't work (it says the function itoa
doesn't exist).
推荐答案
使用 sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
int
可以表示的所有数字都将适合 12 字符数组而不会溢出,除非您的编译器以某种方式为 int
使用超过 32 位.当使用具有更大位大小的数字时,例如long
对于大多数 64 位编译器,您需要增加数组大小——对于 64 位类型,至少 21 个字符.
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.
这篇关于如何在C中将整数转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文