Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4733323
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: LINUX

2009-02-27 14:20:17


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


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