MFlower——朝花夕拾

                                   有你有我
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

同一个数字数据在 int 和 string 类型转换

Posted on 2008-11-26 01:57  MFlower  阅读(129)  评论(0)    收藏  举报

例如:

"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;
}

 

输出:

ival:45

strval:45