zoukankan      html  css  js  c++  java
  • 字符串函数---itoa()函数具体解释及实现

    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='';
    	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;
    }

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



  • 相关阅读:
    C++ UNREFERENCED_PARAMETER函数的作用
    Win32 Console Application、Win32 Application、MFC三者之间的联系和区别
    解决CSDN博客插入代码出现的问题
    C++ std::vector指定位置插入
    计算机如何与人沟通(1)
    C++ fstream文件操作
    using namespace std 和 include 的区别
    找不到windows.h源文件
    C++ 字符串转换
    WPF style 换肤
  • 原文地址:https://www.cnblogs.com/llguanli/p/6773538.html
Copyright © 2011-2022 走看看