用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字

苦瓜爱代码    -  云代码空间

——

atoi

2014-09-25|1466阅||

摘要:把字符转换为整数

atoi()函数的功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回(返回转换后的整型数)。

    atoi()函数实现的代码:

  1. int my_atoi(char* pstr)  
  2. {  
  3.     int Ret_Integer = 0;  
  4.     int Integer_sign = 1;  
  5.       
  6.     /* 
  7.     * 判断指针是否为空 
  8.     */  
  9.     if(pstr == NULL)  
  10.     {  
  11.         printf("Pointer is NULL\n");  
  12.         return 0;  
  13.     }  
  14.       
  15.     /* 
  16.     * 跳过前面的空格字符 
  17.     */  
  18.     while(isspace(*pstr) == 0)  
  19.     {  
  20.         pstr++;  
  21.     }  
  22.       
  23.     /* 
  24.     * 判断正负号 
  25.     * 如果是正号,指针指向下一个字符 
  26.     * 如果是符号,把符号标记为Integer_sign置-1,然后再把指针指向下一个字符 
  27.     */  
  28.     if(*pstr == '-')  
  29.     {  
  30.         Integer_sign = -1;  
  31.     }  
  32.     if(*pstr == '-' || *pstr == '+')  
  33.     {  
  34.         pstr++;  
  35.     }  
  36.       
  37.     /* 
  38.     * 把数字字符串逐个转换成整数,并把最后转换好的整数赋给Ret_Integer 
  39.     */  
  40.     while(*pstr >= '0' && *pstr <= '9')  
  41.     {  
  42.         Ret_Integer = Ret_Integer * 10 + *pstr - '0';  
  43.         pstr++;  
  44.     }  
  45.     Ret_Integer = Integer_sign * Ret_Integer;  
  46.       
  47.     return Ret_Integer;  
  48. }  
顶 0踩 0收藏
文章评论
    发表评论

    个人资料

    • 昵称: 苦瓜爱代码
    • 等级: 中级程序员
    • 积分: 235
    • 代码: 8 个
    • 文章: 2 篇
    • 随想: 0 条
    • 访问: 4 次
    • 关注

    标签

    最新提问

      站长推荐