分类: LINUX
2010-07-30 15:27:40
首先,我们先看看微软对于该功能的实现。
C/C++ code
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 <stdlib.h>
#include <stdio.h>
int myatoi(char *str)
{
int ret = 0;
int sign = 1;
if(*str == '-')
sign = -1;
else
ret = ret *10 + (*str - '0');
str++;
while(* '\0')
{
ret = ret *10 + (*str - '0');
str++;
}
return sign*ret;
}
void main()
{
char *mystring = "123";
int i = myatoi(mystring);
printf("i value:%d\n",i);
getch();
}