例如:
"45"->45
45->"45"
即平常所说的 atoi() 和 itoa() 这两个函数的作用。为了与系统函数的区别,下面使用 myatoi() 和 myitoa() 表示
int myatoi(const char *src)
{
int total = 0;
while (*src)
{
total = total*10 + (int)(*src - '0');
src++;
}
return total;
}
char* myitoa(int n,char *str)
{
char* temp = str;
int len = 0, x = n;
while(x != 0)
{
++len;
x = x /10;
}
for(int i = len-1; i >= 0;--i)
{
str[i] = n % 10 + 48;
n = n /10;
}
str[len] = '\0';
return temp;
}
void main()
{
char *val = "45";
int ival = myatoi(val);
cout<<"ival:"<<ival<<endl;
char str[10];
myitoa(45,str);
cout<<"strval:"<<str<<endl;
}
{
int total = 0;
while (*src)
{
total = total*10 + (int)(*src - '0');
src++;
}
return total;
}
char* myitoa(int n,char *str)
{
char* temp = str;
int len = 0, x = n;
while(x != 0)
{
++len;
x = x /10;
}
for(int i = len-1; i >= 0;--i)
{
str[i] = n % 10 + 48;
n = n /10;
}
str[len] = '\0';
return temp;
}
void main()
{
char *val = "45";
int ival = myatoi(val);
cout<<"ival:"<<ival<<endl;
char str[10];
myitoa(45,str);
cout<<"strval:"<<str<<endl;
}
输出:
ival:45
strval:45
浙公网安备 33010602011771号