c/c++语言开发共享C语言模拟实现库函数atoi

c语言模拟实现库函数atoi,atoi() 函数用来将字符串转换成整数(int),其原型为: int atoi (const char * str); 【函数说明】atoi() 函数会扫描参数 st

c语言模拟实现库函数atoi,atoi() 函数用来将字符串转换成整数(int),其原型为:
int atoi (const char * str);

【函数说明】atoi() 函数会扫描参数 str 字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过 isspace() 函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(‘’)才结束转换,并将结果返回。

【返回值】返回转换后的整型数;如果 str 不能转换成 int 或者 str 为空字符串,那么将返回 0。

  #include     #include     #include     #include       int my_atoi(char const *p)  {      int ret = 0;      int a = 0;      int flag = 1;      assert(p != null);      while (isspace(*p))      {          p++;      }      while (*p)      {          if (*p == '+')              p++;          else if (*p == '-')          {              p++;              flag = -1;          }          else if (*p >= '0'&& *p <= '9')          {              a = *p - '0';              ret = (ret * 10 + a);              p++;          }          else              return 0;      }      if ((flag == 1 && ret > 0x7fffffff) || (flag == -1 && ret < (signed int)0x80000000))          return 0;      return ret*flag;  }    int main()  {      printf("%dn", my_atoi(" +2345"));      printf("%dn", my_atoi(" -2345"));      printf("%dn", my_atoi("+2345"));      printf("%dn", my_atoi("-2345"));      printf("%dn", my_atoi("2345"));      printf("%dn", my_atoi("2345"));      printf("%dn", my_atoi(""));      printf("%dn", my_atoi("123ab"));      system("pausen");      return 0;  }

C语言模拟实现库函数atoi

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/607200.html

(1)
上一篇 2021年5月14日
下一篇 2021年5月14日

精彩推荐