如何转换int到字符串在C?

如何将int(整数)转换为字符串?我正在尝试创建一个函数,该函数将struct的数据转换为字符串,以便将其保存在文件中。

1355341 次浏览

你可以使用sprintf来做,如果你有的话,也可以使用snprintf:

char str[ENOUGH];
sprintf(str, "%d", 42);

str中的字符数(加上终止字符)可以使用以下方法计算:

(int)((ceil(log10(num))+1)*sizeof(char))

正如评论中指出的,itoa()不是标准,所以最好使用对应答案中建议的sprintf()方法!


可以使用itoa()函数将整数值转换为字符串。

这里有一个例子:

int num = 321;
char snum[5];


// convert 123 to string [buf]
itoa(num, snum, 10);


// print our string
printf("%s\n", snum);

如果您想将结构输出到文件中,则不需要事先转换任何值。你可以只使用Printf格式规范来指示如何输出你的值,并使用printf的家庭中的任何操作符来输出你的数据。

如果您想将结构输出到文件中,则不需要事先转换任何值。您可以只使用printf格式规范来指示如何输出值,并使用printf系列中的任何操作符来输出数据。

这是老方法,但还有另一种方法。

#include <stdio.h>


#define atoa(x) #x


int main(int argc, char *argv[])
{
char *string = atoa(1234567890);
printf("%s\n", string);
return 0;
}

在查看了gcc的各种版本的itoa之后,我发现能够处理到二进制、十进制和十六进制(正数和负数)的转换的最灵活的版本是在http://www.strudel.org.uk/itoa/中找到的第四个版本。虽然sprintf/snprintf有优势,但除了十进制转换外,它们不能处理负数。由于上面的链接要么离线要么不再活跃,我在下面列出了他们的第4个版本:

/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }


char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;


do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );


// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
/*Function return size of string and convert signed  *
*integer to ascii value and store them in array of  *
*character with NULL at the end of the array        */


int itoa(int value,char *ptr)
{
int count=0,temp;
if(ptr==NULL)
return 0;
if(value==0)
{
*ptr='0';
return 1;
}


if(value<0)
{
value*=(-1);
*ptr++='-';
count++;
}
for(temp=value;temp>0;temp/=10,ptr++);
*ptr='\0';
for(temp=value;temp>0;temp/=10)
{
*--ptr=temp%10+'0';
count++;
}
return count;
}

如果您正在使用GCC,您可以使用GNU扩展asprintf函数。

char* str;
asprintf (&str, "%i", 12313);
free(str);

简单的回答是:

snprintf( str, size, "%d", x );

较长的是:首先你需要找到足够的大小。snprintf告诉你长度,如果你用NULL, 0作为第一个参数调用它:

snprintf( NULL, 0, "%d", x );

为空结束符再分配一个字符。

#include <stdio.h>
#include <stdlib.h>


int x = -42;
int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);

If适用于所有格式字符串,因此可以使用"%g"将float或double转换为字符串,使用"%x"将int转换为十六进制,等等。

将任何东西转换为字符串应该1)分配结果字符串或2)传递char *目标和大小。示例代码如下:

两者都适用于所有int,包括INT_MIN。它们提供一致的输出,而不像snprintf()那样依赖于当前的语言环境。

方法1:内存不足时返回NULL

#define INT_DECIMAL_STRING_SIZE(int_type) ((CHAR_BIT*sizeof(int_type)-1)*10/33+3)


char *int_to_string_alloc(int x) {
int i = x;
char buf[INT_DECIMAL_STRING_SIZE(int)];
char *p = &buf[sizeof buf] - 1;
*p = '\0';
if (i >= 0) {
i = -i;
}
do {
p--;
*p = (char) ('0' - i % 10);
i /= 10;
} while (i);
if (x < 0) {
p--;
*p = '-';
}
size_t len = (size_t) (&buf[sizeof buf] - p);
char *s = malloc(len);
if (s) {
memcpy(s, p, len);
}
return s;
}

方法2:如果缓冲区太小,它返回NULL

static char *int_to_string_helper(char *dest, size_t n, int x) {
if (n == 0) {
return NULL;
}
if (x <= -10) {
dest = int_to_string_helper(dest, n - 1, x / 10);
if (dest == NULL) return NULL;
}
*dest = (char) ('0' - x % 10);
return dest + 1;
}


char *int_to_string(char *dest, size_t n, int x) {
char *p = dest;
if (n == 0) {
return NULL;
}
n--;
if (x < 0) {
if (n == 0) return NULL;
n--;
*p++ = '-';
} else {
x = -x;
}
p = int_to_string_helper(p, n, x);
if (p == NULL) return NULL;
*p = 0;
return dest;
}

[编辑]应@Alter Mann的要求

(CHAR_BIT*sizeof(int_type)-1)*10/33+3至少是将某个有符号整数类型编码为由可选的负号、数字和空字符组成的字符串所需的char的最大数目。

有符号整数中的非符号位数不超过CHAR_BIT*sizeof(int_type)-1。以10为基数表示的__abc1位二进制数最多包含n*log10(2) + 1位。10/33略大于log10(2)。+1表示符号char, +1表示空字符。其他分数也可以用28/93。


方法3:如果一个人想要生活在边缘,缓冲区溢出不是一个问题,一个简单的C99或更高的解决方案,处理所有 int

#include <limits.h>
#include <stdio.h>


static char *itoa_simple_helper(char *dest, int i) {
if (i <= -10) {
dest = itoa_simple_helper(dest, i/10);
}
*dest++ = '0' - i%10;
return dest;
}


char *itoa_simple(char *dest, int i) {
char *s = dest;
if (i < 0) {
*s++ = '-';
} else {
i = -i;
}
*itoa_simple_helper(s, i) = '\0';
return dest;
}


int main() {
char s[100];
puts(itoa_simple(s, 0));
puts(itoa_simple(s, 1));
puts(itoa_simple(s, -1));
puts(itoa_simple(s, 12345));
puts(itoa_simple(s, INT_MAX-1));
puts(itoa_simple(s, INT_MAX));
puts(itoa_simple(s, INT_MIN+1));
puts(itoa_simple(s, INT_MIN));
}

样例输出

0
1
-1
12345
2147483646
2147483647
-2147483647
-2147483648

使用函数itoa()整数转换为字符串

例如:

char msg[30];
int num = 10;
itoa(num,msg,10);

sprintf返回字节并添加空字节:

# include <stdio.h>
# include <string.h>
int main() {
char buf[ 1024];
int n = sprintf( buf, "%d", 2415);
printf( "%s %d\n", buf, n);
}


输出:

2415 4