follow my heart...
分类: C/C++
2009-02-23 16:22:36
long atol(const char *nptr)
{
int c; /* current char */
long total; /* current total */
int sign; /* if '-', then negative, otherwise positive */
/* skip whitespace */
while ( isspace((int)(unsigned char)*nptr) )
++nptr;
c = (int)(unsigned char)*nptr++;
sign = c; /* save sign indication */
if (c == '-' || c == '+')
c = (int)(unsigned char)*nptr++; /* skip sign */
total = 0;
while (isdigit(c)) {
total = 10 * total + (c - '0'); /* accumulate digit */
c = (int)(unsigned char)*nptr++; /* get next char */
}
if (sign == '-')
return -total;
else
return total; /* return result, negated if necessary */
}
int atoi(const char *nptr)
{
return (int)atol(nptr);
}
下面是对该功能的收藏:
#include
#include
int myatoi(char *str)
{
int ret = 0;
int sign = 1;
if(*str == '-')
sign = -1;
else
ret = ret *10 + (*str - '0');
str++;
while(*str!= '\0')
{
ret = ret *10 + (*str - '0');
str++;
}
return sign*ret;
}