且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-03 08:47:14

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