atoi实现

来源:互联网 发布:秀图软件 编辑:程序博客网 时间:2024/06/06 16:39

  1.  atoi()函数的功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回(返回转换后的整型数)。
  2. /* 
  3. * file_name:my_atoi.c 
  4. * function:int my_atoi(char* pstr) 
  5. */  
  6.   
  7. int my_atoi(char* pstr)  
  8. {  
  9.     int Ret_Integer = 0;  
  10.     int Integer_sign = 1;  
  11.       
  12.     /* 
  13.     * 判断指针是否为空 
  14.     */  
  15.     if(pstr == NULL)  
  16.     {  
  17.         printf("Pointer is NULL\n");  
  18.         return 0;  
  19.     }  
  20.       
  21.     /* 
  22.     * 跳过前面的空格字符 
  23.     */  
  24.     while(isspace(*pstr) == 0)  
  25.     {  
  26.         pstr++;  
  27.     }  
  28.       
  29.     /* 
  30.     * 判断正负号 
  31.     * 如果是正号,指针指向下一个字符 
  32.     * 如果是符号,把符号标记为Integer_sign置-1,然后再把指针指向下一个字符 
  33.     */  
  34.     if(*pstr == '-')  
  35.     {  
  36.         Integer_sign = -1;  
  37.     }  
  38.     if(*pstr == '-' || *pstr == '+')  
  39.     {  
  40.         pstr++;  
  41.     }  
  42.       
  43.     /* 
  44.     * 把数字字符串逐个转换成整数,并把最后转换好的整数赋给Ret_Integer 
  45.     */  
  46.     while(*pstr >= '0' && *pstr <= '9')  
  47.     {  
  48.         Ret_Integer = Ret_Integer * 10 + *pstr - '0';  
  49.         pstr++;  
  50.     }  
  51.     Ret_Integer = Integer_sign * Ret_Integer;  
  52.       
  53.     return Ret_Integer;  
  54. }  
0 0
原创粉丝点击