Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8322727
  • 博文数量: 1413
  • 博客积分: 11128
  • 博客等级: 上将
  • 技术积分: 14685
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-13 10:03
个人简介

follow my heart...

文章分类

全部博文(1413)

文章存档

2013年(1)

2012年(5)

2011年(45)

2010年(176)

2009年(148)

2008年(190)

2007年(293)

2006年(555)

分类: C/C++

2009-02-23 16:22:36

首先,我们先看看微软对于该功能的实现。
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
#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;
}

void main()
{
        char *mystring = "123";
        int i = myatoi(mystring);
        printf("i value:%d\n",i);
        getch();
}

阅读(970) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~