如何将整型(整数)转换为字符串?

我试图使一个函数转换成一个字符串的结构数据保存在文件中。


当前回答

/*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;
     }

其他回答

简单的回答是:

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”将浮点数或双精度浮点数转换为字符串,使用“%x”将int数转换为十六进制,等等。

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
/*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;
     }

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

例如:

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

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

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

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

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