如何将整型(整数)转换为字符串?
我试图使一个函数转换成一个字符串的结构数据保存在文件中。
如何将整型(整数)转换为字符串?
我试图使一个函数转换成一个字符串的结构数据保存在文件中。
当前回答
在查看了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;
}
其他回答
简单的回答是:
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数转换为十六进制,等等。
如果您正在使用GCC,您可以使用GNU扩展asprintf函数。
char* str;
asprintf(&str, "%i", 12313);
free(str);
/*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
使用函数itoa()将整数转换为字符串
例如:
char msg[30];
int num = 10;
itoa(num,msg,10);