概述
atoi和itoa是C中两个常见的函数,功能是进行字符和数字来回转换,原型如下:
int atoi(const char *nptr); //nptr是要转换的字符串,返回转换后的整数。
char *itoa( int value, char *string, int radix); //value是要转换的整数,string是接受的转换后字符串,返回的也是这个, radix是几进制,如2,10分别表示二进制,10进制。
itoa函数的头文件是stdio.h, 它并不是一个标准的C函数,而是Windows特有的,如果在linux系统使用itoa函数,编译会通不过。两种方式可替代:
1, sprintf函数
int main()
{
int n=233;
char s[32]={0};
sprintf(s,"%d",n);
printf("sprintf, int2str, s= %sn",s);
}
2,自写实现
下面分别给了使用stdio.h库的atoi, itoa函数调用方式,以及自写的c++实现方式。
#include<iostream>
using namespace std;
int str2int(const char *str)
{
int temp = 0;
const char *ptr = str; //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;
}
void int2str(int n, char *str)
{
char buf[10] = "";
int i = 0;
int len = 0;
int temp = n < 0 ? -n: n; // temp为n的绝对值
if (str == NULL)
{
return;
}
while(temp)
{
buf[i++] = (temp % 10) + '0'; //把temp的每一位上的数存入buf
temp = temp / 10;
}
len = n < 0 ? ++i: i; //如果n是负数,则多需要一位来存储负号
str[i] = 0; //末尾是结束符0
while(1)
{
i--;
if (buf[len-i-1] ==0)
{
break;
}
str[i] = buf[len-i-1]; //把buf数组里的字符拷到字符串
}
if (i == 0 )
{
str[i] = '-'; //如果是负数,添加一个负号
}
}
int ll2str(char *s, long long value,int radix) {
char *p, aux;
unsigned long long v;
size_t l;
/* Generate the string representation, this method produces
* an reversed string. */
v = (value < 0) ? -value : value;
p = s;
do {
*p++ = '0' + (v % radix); // 2
v /= radix; // 2
} while (v);
if (value < 0) *p++ = '-';
/* Compute length and add null term. */
l = p - s;
*p = '