新整理资料大全

来源:互联网 发布:淘宝无法登陆 编辑:程序博客网 时间:2024/06/02 14:16
atoi atol实现
2009-10-16 15:49

long atol(const char *nptr);
函数说明:
atol()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('/0')才结束转换,并将结果返回。
返回值:     返回转换后的长整型数

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

 

 

 

int __cdecl strcmp(const char *src,const char *dst)     
{     
    int   ret=0;     
   
    while(!(ret=*(unsigned char *)src-*(unsigned char *)dst) && *dst)     
               ++src,++dst;     
    
    if(ret<0)     
         ret=-1;     
    else if(ret>0)     
         ret=1;     

    return ret;     
}

函数原型:int strcmp(const char *dest, const char *source) ;
返回值:返回整数值,如果dest > source,则返回值大于0,如果dest = source,则返回值等于0,如果dest < source ,则返回值小于0。字符大小是按照字符的字典序列进行排列的。

参数说明:都是以''/0''为结束符的字符串

实现;
int strcmp(const char *dest, const char *source)  
{  
   assert((NULL != dest) && (NULL != source));  
   while (*dest && *source && (*dest == *source))  
          {  
               dest ++;  
               source ++;  
           }  
   return *dest - *source;  
   /*如果dest > source,则返回值大于0,如果dest = source,则返回值等于0,如果dest < source ,则返回值小于0。*/
}

原创粉丝点击