C语言模拟实现atoi函数的实例详解

时间:2019-03-31
本文章向大家介绍C语言模拟实现atoi函数的实例详解,主要包括C语言模拟实现atoi函数的实例详解使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

C语言模拟实现atoi函数的实例详解

atoi函数,主要功能是将一个字符串转变为整数,例如将“12345”?>12345。但在实现过程中,我们难免会因为考虑不够全面而漏掉比较重要的几点,今天就总结一下实现atoi函数需要注意的地方。

1.指针为NULL
2.字符串为空字符串
3.空白字符
4.正号与负号问题
5.溢出问题
6.异常字符处理

接下来看代码:(具体几种问题处理都在代码的注释中说明)

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>

//定义两个枚举常量来表示状态
enum STATE
{
  VALID, //合法
  INVALID,//非法
};
enum STATE state = INVALID;
int my_atoi(const char *str)
{
  int flag = 1;
  long long ret = 0;//定义为比int存储范围还要大的类型,防止后面判断溢出时出错。
  //空指针
  assert(str);
  //空字符串
  if (*str == "\0")
  {
    return 0;
  }
  //空白字符
  while (isspace(*str))//用函数isspace判断是否为空白字符
  {
    str++;
  }
  //遇到正负号
  if (*str == '-')
  {
    flag = -1;
    str++;
  }
  if (*str == '+')
  {
    str++;
  }
  //
  while (*str)
  {
    //if (*str >= '0'&&*str <= '9')
    if (isdigit(*str))//用函数isdigit判断是否为数字字符
    {
      ret = ret * 10 + flag*(*str - '0');
      //判断是否溢出
      if (ret > INT_MAX || ret < INT_MIN)
      {
        return ret;
      }
    }
    //异常字符
    else
    {
      break;
    }
    str++;
  }
  state = VALID;
  return ret;
}
int main()
{
  char *p = "12345";
  char *q = " -12345";
  int ret = my_atoi(p);
  int ret2 = my_atoi(q);
  printf("%d\n", ret);
  printf("%d\n", ret2);
  system("pause");
  return 0;
}

运行结果:

以上就是C语言模拟实现atoi函数的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!