string和int間的類型轉換 (轉)

http://www.cppblog.com/dqchen/archive/2006/12/10/16215.aspx

int 轉換 string

string  int2str( int  num)
 {
   
if (num  ==   0 )
      
return   " 0 " ;
   
   
string  str  =   "" ;
   
int  num_  =  num  >   0   ?  num :  - 1   *  num;

   
while (num_)
   
 {
      str 
=  ( char )(num_  %   10   +   48 +  str;
      num_ 
/=   10 ;
    }


   
if (num  <   0 )
      str 
=   " - "   +  str;

   
return  str;
}

string 轉換 int
 Implementing itoa function is a popular interview question. Here’s one implementation from SAP.

char *itoa(int value)
{
int count, /* number of characters in string */
i, /* loop control variable */
sign; /* determine if the value is negative */
char *ptr, /* temporary pointer, index into string */
*string, /* return value */
*temp; /* temporary string array */

count = 0;
if ((sign = value) < 0) /* assign value to sign, if negative */
{ /* keep track and invert value */
value = -value;
count++; /* increment count */
}

/* allocate INTSIZE plus 2 bytes (sign and NULL) */
temp = (char *) malloc(INTSIZE + 2);
if (temp == NULL)
{
return(NULL);
}
memset(temp,'/0', INTSIZE + 2);

string = (char *) malloc(INTSIZE + 2);
if (string == NULL)
{
return(NULL);
}
memset(string,'/0', INTSIZE + 2);
ptr = string; /* set temporary ptr to string */

/*--------------------------------------------------------------------+
| NOTE: This process reverses the order of an integer, ie: |
| value = -1234 equates to: char [4321-] |
| Reorder the values using for {} loop below |
+--------------------------------------------------------------------*/
do {
*temp++ = value % 10 + '0'; /* obtain modulus and or with '0' */
count++; /* increment count, track iterations*/
} while (( value /= 10) >0);

if (sign < 0) /* add '-' when sign is negative */
*temp++ = '-';

*temp-- = '/0'; /* ensure null terminated and point */
/* to last char in array */

/*--------------------------------------------------------------------+
| reorder the resulting char *string: |
| temp - points to the last char in the temporary array |
| ptr - points to the first element in the string array |
+--------------------------------------------------------------------*/
for (i = 0; i < count; i++, temp--, ptr++)
{
memcpy(ptr,temp,sizeof(char));
}

return(string);
}

int  str2int( string  str)
  {
   
int  i,len  =  str.size(),num  =   0 ;

    i 
=   0 ;   
   
if (str[ 0 ==   ' - ' )
      i 
=   1 ;
   
   
while (i  <  len)
   
 {
      num 
=  num  *   10   +  ( int )(str[i]  -   ' 0 ' );
      i
++ ;
    }


   
if (str[ 0 ==   ' - ' )
      num 
*=   - 1 ;

   
return  num;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章