一、数字转换为字符串
char *itoa(int value, char *string, int radix)
返回值:指向string这个字符串的指针
char *p=new char; //或者定义char p[25];
int a=108;
itoa(a,p,10);
cout<<itoa(a,p,10)<<endl; //输出108
cout<<p<<endl; //输出108
itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用 的基数。在上例中,转换基数为10。10:十进制;2:二进制…
itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似:
char str[255];
sprintf(str, “%x”, 100); //将100转为16进制表示的字符串。
二、atoi()——把字符串转换成整型数
将字符串转换为整数的函数在stdlib.h中定义:
int atoi(const char *str);
int atoi (char s[])
{
int i,n,sign;
for(i=0;isspace(s[i]);i++)//跳过空白符;
sign=(s[i]==’-‘)?-1:1;
if(s[i]==’+’||s[i]==’ -‘)//跳过符号
i++;
for(n=0;isdigit(s[i]);i++)
n=10*n+(s[i]-‘0’);//将数字字符转换成整形数字
return sign *n;
}