1.将整型转换成字符串:
#define my_maxlen 100
void int2str(int num, char* str)
{
int index = 0, len = 0;
char buf[my_maxlen] = "";
if (num < 0)
{
num = -num;
str[index++] = '-';
}
while ( num > 0 )
{
buf[len++] = (num % 10) + '0';
num /= 10;
}
buf[len] = '\0';
while ( len > 0 )
{
str[index++] = buf[--len];
}
str[index] = '\0';
}
2.将字符串转换成整型:
int str2int(const char* str)
{
int temp = 0;
const char* ptr = str;
if ( *str == '-' || *str == '+' )
{
str++;
}
while ( *str != '\0' )
{
if ( ( *str < '0') || ( *str > '9' ) )
{
break;
}
temp = temp * 10 + (*str - '0');
str++;
}
if ( *ptr == '-' )
{
temp = -temp;
}
return temp;
}