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

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


当前回答

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

其他回答

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

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

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

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

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

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

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

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

例如:

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