模拟实现atoi函数

简介: 模拟实现atoi函数

一、atoi函数的功能

atoi函数的功能是将字符串转换为整数 ,并且该函数能转换正负数,和对字符串前面的空格进行跳跃,遇到数字进行转换,遇到非数字字符转换结束,还有若转换成整数越界也无法转换。

二、模拟实现

#include<stdio.h>
#include<ctype.h>
#include<limits.h>
enum Statue
{
  normal,
  abnormal
 
};
Statue statue = abnormal;
int my_auti(const char* str)
{
  int flag = 0;
  if (*str == NULL || *str == '\0')
  {
    return 0;
  }
  while (isspace(*str))
  {
    str++;//对空格进行跳跃
  }
  if (*str == '-')
  {
    flag = -1;
    str++;
 
  }
  else if (*str == '+')
  {
    flag = 1;
    str++;
  }
  else
  {
    flag = 1;
  }
  
  long long sum = 0;
  while (isdigit(*str))
  {
  
    sum = (*str-'0') * flag + sum * 10;
    if (sum<INT_MIN || sum>INT_MAX)
    {
      return 0;
    }
    str++;
  }
  if (*str == '\0')
  {
    statue = normal;
    return sum;
  }
  else
  {
    return sum;
  }
}
int main()
{
  char str[30] = "  -499";
  int ret = my_auti(str);
  if (statue == normal)
  {
    printf("正常转换:%d\n", ret);
  }
  else
  {
    printf("异常转换:%d\n", ret);
  }
  return 0;
}

运行结果:



目录
相关文章
|
8月前
|
C语言
strlen函数【详解+模拟实现】
strlen函数【详解+模拟实现】
|
7天前
atoi函数(想要彻底了解atoi函数,那么看这一篇就足够了!)
atoi函数(想要彻底了解atoi函数,那么看这一篇就足够了!)
|
9月前
strstr函数的使用及模拟实现
1.strstr函数 2.strstr函数的使用 3.strstr函数的模拟实现
79 0
|
1月前
atoi()详解及其模拟实现
atoi()详解及其模拟实现
|
1月前
atoi函数的模拟实现
atoi函数的模拟实现
|
11月前
|
存储 Serverless
strlen函数解析与模拟实现
strlen函数解析与模拟实现
strlen函数解析与模拟实现
|
10月前
模拟实现atoi函数
模拟实现atoi函数
|
10月前
strlen函数的两种模拟方法以及使用
strlen函数的两种模拟方法以及使用
|
11月前
模拟实现atoi
模拟实现atoi
33 0
|
C++
strlen 的三种模拟方法
strlen 的三种模拟方法
76 0
strlen 的三种模拟方法