atoi()函数及其实现

atoi()函数原型:int atoi(const char *nptr)
用法:#include <stdlib.h>
功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回。
说明:atoi()函数返回转换后的整型数。

用法如下:

#include<stdio.h>  
#include<stdlib.h>   
int main()  
{  
    char a[] = "-100";  
    char b[] = "456";  
    int c = 0;       
    c = atoi(a) + atoi(b);      
    printf("c = %d\n",c);  
}

atoi()函数的代码实现:

/*
* file_name:my_atoi.c 
* function:int my_atoi(char* pstr) 
*/
int my_atoi(char* pstr)  
{  
    int Ret_Integer = 0;  
    int Integer_sign = 1;   
    if(pstr == NULL)             //判断指针是否为空  
    {  
        printf("Pointer is NULL\n");  
        return 0;  
    }    
    while(isspace(*pstr) == 0)  //跳过前面的空格字符 
    {  
        pstr++;  
    }   
    /* 
    * 判断正负号 
    * 如果是正号,指针指向下一个字符 
    * 如果是负号,把符号标记为Integer_sign置-1,然后再把指针指向下一个字符 
    */  
    if(*pstr == '-')  
    {  
        Integer_sign = -1;  
    }  
    if(*pstr == '-' || *pstr == '+')  
    {  
        pstr++;  
    }    
    /* 
    * 把数字字符串逐个转换成整数,并把最后转换好的整数赋给Ret_Integer 
    */  
    while(*pstr >= '0' && *pstr <= '9')  
    {  
        Ret_Integer = Ret_Integer * 10 + *pstr - '0';  
        pstr++;  
    }  
    Ret_Integer = Integer_sign * Ret_Integer;  
      
    return Ret_Integer;  
}  
原文地址:https://www.cnblogs.com/sooner/p/3038085.html