
功 能: 把一整数转换为字符串
用 法: char *itoa(int value, char *string, int radix);
帮帮我好么? 谢谢啦!
这个函数网上很容易找到其源码。上面那位“abcd1236386”给的代码,其实也没问题,但是如果你转换的超出10进制数,那就不能正确显示了。我这里提供的是可以正确显示的,能提供转换2-36进制的数。使用
table[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";这里最多是 Z = 35。
可根据需要扩充table[]。
下面我用C++写隐郑了一个使用这个函数的代码,如果你使用的是C语言,那么可以自己相应做一些改变。另灶郑颂外,我使用的是VC6.0编译器,如果你用TC或其他编译器,语法上有一些小改变,自己修改。
#include
#include <丛迟cstring>
using namespace std;
char *my_itoa(int num,char *str,int radix);//num为需转换整数,str为字符串首字符地址,radix为转换后的进制数
int main()
{
int a,r;
char *s = new char [100] ; //先申请空间
char *c;
c = (char *)s; //把s指向的地址空间的首字符地址赋给c,便于使用my_itoa函数
cout<<"请输入需要转换为字符串的整数:\n";
cin>>a;
cout<<"\n输入希望转换为的基数,比如转换为2进制数请输入2:\n";
cin>>r;
my_itoa(a,c,r);
cout<<"\n"<
}
char *my_itoa(int num,char *str,int radix)
{
const char table[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *ptr = str;
bool negative = false;
if(num == 0)
{ //num=0
*ptr++='0';
*ptr='\0'; // don`t forget the end of the string is '\0'!!!!!!!!!
return str;
}
if(num<0)
{ //if num is negative ,the add '-'and change num to positive
*ptr++='-';
num*=-1;
negative = true;
}
while(num)
{
*ptr++ = table[num%radix];
num/=radix;
}
*ptr = '\0'; //if num is negative ,the add '-'and change num to positive
// in the below, we have to converse the string
char *start = (negative ? str+1 : str); //now start points the head of the string
ptr--; //now prt points the end of the string
while(start
char temp = *start;
*start = *ptr;
*ptr = temp;
start++;
ptr--;
}
return str;
}
我觉得是这样的
char*itoa(int value,char*string,int radix)
{
int count=0;
int temp=value;
do{count++;}while(temp/核卜庆=radix);//总共多少位弊吵
char *itoa_des=string;
string+=count-1;
*(string+1)=0;
while(count--)
{
*string--=value%radix+'0';
value/=radix;
}
return itoa_des;
}
调试通过改握了
这种问题网银纯上锋袭咐一大把禅尘
http://blog.csdn.net/qiutaox/archive/2008/11/20/3342037.aspx
可不可以补充一下 你函数3个参数具体意义
你要干啥啊?
要功能知道了,但是参数是啥意思,你要怎么用,给个你想像中用法的例子吧。