atoi()函数和itoa()函数的用法及其实现(字符串与整形的相互转化)

atoi()及itoa()的用法

一.itoa()的用法

1.原型:char itoa(int value, char string, int radix)
2.头文件:include<stdlib.h>
3.功能:将整数value转换成字符串存入string,radix为转换所用基数(分别为 2进制, 8进制, 10进制, 16进制)
4.返回值:转换后的字符串的指针
举例:

void Test1()
{
	int a = 12345;
	char s[25];

	itoa(a, s, 10);
	printf("%s", s);

}

结果:发现错误
在这里插入图片描述

原因:

新版本的vs对旧有的函数itoa进行了安全检查,所以使用新版本的vs会提示错误,而旧版本的没问题。

解决方法:

  • 1、使用新函数 _itoa
  • 2、加上宏定义
  • #define _CRT_NONSTDC_NO_DEPRECATE
    #define _CRT_SECURE_NO_WARNINGS
    在这里插入图片描述

二.atoi的用法

1.原型:int atoi(const char* nptr)
2.头文件 stdlib.h
3.功能:跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(’\0’)才结束转换,并将结果返回。
4.返回值:成功返回转换后的数值,失败则返回0.
举例:

void Test()
{
	string s("1234");
	int c = atoi(s.c_str());//先将string类型转换为char*类型,再通过atoi函数将字符数字转换为整形数字
	cout << c << endl;
}

结果:
在这里插入图片描述

atoi()函数及itoa()函数的实现

atoi()实现

int my_atoi(const char* str)
{
	int cur = 0;
	const char* pur = str;
	
	if (*str == '+' || *str == '-')//如果开头是正数或者负数,跳过
		str++;
	while (*str != '0')
	{
		if (*str > '9' || *str < '0')//如果出现除字符数字以外的字符,跳出循环
			break;

		if (*str >= '0' && *str <= '9')
		{
			cur = cur * 10 + *str - '0';//给cur的最低位加上字符数字
		}
		str++;
	}
	if (*pur == '-')//判断字符串的开头是正数还是负数
		return cur * -1;
	return cur;
}
void Test()
{
	char s[] = "12345";
	int c = my_atoi(s);
	cout << c << endl;
}

在这里插入图片描述

itoa()函数实现

简单实现:

char* my_itoa(int n, char str[])
{
	int count = n;
	int i = 0;
	if (count < 0)//如果是负数,转换为正数
	{
		n = -n;
	}

	while (n > 0)
	{
		str[i++] = n % 10 + '0';//+‘0’转换为字符数
		n /= 10;
	}

	if (count < 0)
	{
		str[i++] = '-';
	}

	str[i] = '\0';
	for (int j = i - 1, i = 0; j > i; j--, i++)//由于存入的时候是逆序,现在要反转过来
	{
		str[j] ^= str[i];
		str[i] ^= str[j];
		str[j] ^= str[i];
		//swap(str[i], str[j]);

	}
	return str;

}

void Test1()
{
	int a = 12345;
	char s[25];

	char* s1 = my_itoa(123, s);
	printf("%s", s1);

}

结果:
在这里插入图片描述
考虑进制位

char* my_itoa2(int n,char str[],int radix=10)
{
    int i,j,len,sign;
    unsigned int tmp;
    i = 0;
    if(n<0)    //
    {
        tmp = MY_MAX + n + 1;// 这样貌似可以了,按照取反加一的方式进行的
        do{
            str[i++]=__itoa[tmp%radix];    //取下一个数字
        }while((tmp/=radix)>0);//循环相除
    }
    else
    {
        do{
            str[i++]=__itoa[n%radix];    //取下一个数字
        }while((n/=radix)>0);//循环相除
    }
 
    str[i]='\0';
    len = i;//
    for(j=len-1,i=0;j>i;j--,i++)        //生成的数字是逆序的,所以要交换
    {
		swap(str[j], str[i]);
    }
    return str;
}

猜你喜欢

转载自blog.csdn.net/l477918269/article/details/89639851