您的位置:首页 > 其它

字符串函数---itoa()函数详解及实现

2014-10-10 11:59 232 查看
itoa()函数

itoa():char *itoa( int value, char *string,int radix);

原型说明:

value:欲转换的数据。

string:目标字符串的地址。

radix:转换后的进制数,可以是10进制、16进制等,范围必须在 2-36。

功能:将整数value 转换成字符串存入string 指向的内存空间 ,radix 为转换时所用基数(保存到字符串中的数据的进制基数)。

返回值:函数返回一个指向 str,无错误返回。

itoa()函数实例:

#include<iostream>
#include<string>
using namespace std;

int main()
{
	int i=1024;

	char a[100]={0};

	for(int j=2;j<=36;j++)
	{
		_itoa_s(i,a,j);
		cout<<a<<endl;
	}
	
	system("pause");
	return 0;
}


itoa()函数实现:
#include<iostream>
#include<string>

using namespace std;

char *itoa_my(int value,char *string,int radix)
{
	char zm[37]="0123456789abcdefghijklmnopqrstuvwxyz";
	char aa[100]={0};

	int sum=value;
	char *cp=string;
	int i=0;
	
	if(radix<2||radix>36)//增加了对错误的检测
	{
		cout<<"error data!"<<endl;
		return string;
	}

	if(value<0)
	{
		cout<<"error data!"<<endl;
		return string;
	}
	

	while(sum>0)
	{
		aa[i++]=zm[sum%radix];
		sum/=radix;
	}

	for(int j=i-1;j>=0;j--)
	{
		*cp++=aa[j];
	}
	*cp='\0';
	return string;
}

int main()
{
	int i=1024;

	char a[100]={0};

	for(int j=2;j<=36;j++)
	{
		itoa_my(i,a,j);
		cout<<a<<endl;
	}
	
	system("pause");
	return 0;
}


运行截图与原函数输出一样,均为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: