C問題---atoi() 實現

-------------------------------------
典型例題 21:C問題---atoi() 實現。
-------------------------------------
 1    #include <stdio.h>
 2    #include <string.h>
 3    #include <stdlib.h>
 4    #define  _tchartodigit(c) ((c)>='0' &&(c)<='9'?(c)-'0' : -1)
 5   
 6    int myatoi(const char *str)
 7    {
 8        int i = 0;
 9        int sum = 0;;
10        if(str[0] == '-'||str[0] =='+')
11            {
12                i++;
13            }
14   
15        while((str[i] != '/0')&&(str[i]>='0'&&str[i]<='9'))
16            {
17                sum = sum*10+(str[i]-'0');
18                i++;
19            }
20   
21            if (str[0] == '-')
22                return -sum;
23            else
24                return sum;
25    }
26   
27        long _tstol(const char *nptr ) 
28        { 
29            int   c;                  /*current char*/ 
30            long   total;             /*current total*/ 
31            /* if '-',then negative,otherwise positive*/ 
32            int   sign;                
33            c = (int)(char)*nptr++; 
34            sign = c;                    
35            if(c == ('-') ||c == ('+')) 
36                c = (int)(char)*nptr++; /* skip sign*/ 
37      
38            total = 0; 
39      
40            while ((c = _tchartodigit(c)) != -1 )   { 
41                total   =   10   *   total   +   c; /*accumulate digit*/ 
42                c   =   (char)*nptr++;              /*get next char*/ 
43            } 
44      
45            if   (sign   ==   '-') 
46                return   -total; 
47            else 
48                return   total;   /*return result,negated if necessary*/ 
49        } 
50      
51     
52        int main()
53        {
54            char a[16];
55            bzero(a,16*sizeof(char));
56            printf("please input string:/n");
57            scanf("%s",a);
58            printf("my::atoi :%d/n",myatoi(a));
59            printf("std:atoi :%d/n",atoi(a));
60            printf("std_tstol:%ld/n",_tstol(a));
61            return 0;
62        }

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