如何将整型(整数)转换为字符串?
我试图使一个函数转换成一个字符串的结构数据保存在文件中。
如何将整型(整数)转换为字符串?
我试图使一个函数转换成一个字符串的结构数据保存在文件中。
当前回答
还有另一种方法。
#include <stdio.h>
#define atoa(x) #x
int main(int argc, char *argv[])
{
char *string = atoa(1234567890);
printf("%s\n", string);
return 0;
}
其他回答
/*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))
还有另一种方法。
#include <stdio.h>
#define atoa(x) #x
int main(int argc, char *argv[])
{
char *string = atoa(1234567890);
printf("%s\n", string);
return 0;
}
如果您正在使用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”将浮点数或双精度浮点数转换为字符串,使用“%x”将int数转换为十六进制,等等。