在 C 中创建 atoi 函数

Creating an atoi function in C

我尝试创建 atoi 函数,并认为我编写了正确的代码,但是当我 运行 它时,它显示了错误的代码。我正在尝试弄清楚,但不知道我做错了什么请检查代码并提供一些帮助

我的密码是

#include <stdio.h>

int my_atoi(char *str)
{
  int i;
  int res;
  int sign;

  i = 0;
  res = 0;
  sign = 1;//sign of '-' or '+'
  while(str[i] == ' ' || (str[i] >= 9 && str[i] <= 13))
  {
    i++;
  }
  if(str[i] == '-')
  {
    sign = -1;
    i++;
  }
  else if(str[i] == '+')
  {
    sign = 1;
    i++;
  }
  while(str[i] >= '0' && str[i] <= '9')
  {
    res = res * 10 + str[i] + '0';
    i++;
  }
  return(res * sign);// to make integer which has value of '-' or '+'
}

int main(void)
{
  char str[] = "-2018shiba";
  printf("%d\n", my_atoi(str));
  return(0);
}

当我运行它时,它显示-108674

我看到这里有多个错误。

  1. 如果要将 ASCII 字符转换为相应的整数,您需要减去 '0'。看一下 ASCII table:例如,'7' 被十进制值 55 映射。因此,如果你想得到 7,那么你需要减去 '0' 的 ASCII,即 48 (55 - 48 = 7):
int foo = str[i] - '0';
  1. my_atoi的最后一个while循环中。索引数字字符串表示的值是通过将 str[i] 的值与数字 base 乘以索引 从后面开始 [=37] 的幂来计算的=].
    例如让我们看一下“1337”:

    7*10^0 + 3*10^1 + 3*10^2 + 1*10^3 = 7 + 30 + 300 + 1000 = 1337

    如您所见,7 的数字索引为 0,依此类推。假设你只想忽略 shiba 你的代码看起来像这样 something:

#include <stdio.h>
#include <string.h>

// Return base^(exponent)
int my_pow(int base, unsigned int exponent)
{
  if (exponent == 0) {
    return 1;
  } else {
    int result = base;
    for (int i = 1; i < exponent; i++) {
      result *= base;
    }
    return result;
  }
}

int my_atoi(char *str, size_t len)
{
  int i;
  int res;
  int sign;

  i = 0;
  res = 0;
  sign = 1;//sign of '-' or '+'
  while(str[i] == ' ' || (str[i] >= 9 && str[i] <= 13))
  {
    i++;
  }
  if(str[i] == '-')
  {
    sign = -1;
    i++;
  }
  else if(str[i] == '+')
  {
    sign = 1;
    i++;
  }

  // Store the index where the number string starts
  int j = i-1;
  // Find the ending index of the number string
  i = len;
  while (str[i] < '0' || str[i] > '9') {
      i--;
  }
  int num_end = i;

  // Now start at the ending
  while(i > j)
  {
    if (str[i] >= '0' && str[i] <= '9') {
      res += my_pow(10, num_end-i) * (str[i] - '0');
    } else {
      // If a character unequal to a digit is found then skip it
      num_end--;
    }

    i--;
  }
  return(res * sign);// to make integer which has value of '-' or '+'
}

int main(void)
{
  char str[] = "-2018shiba";
  printf("%d\n", my_atoi(str, strlen(str)));
  char str2[] = "-20X18shiba";
  printf("%d\n", my_atoi(str2, strlen(str2)));
  return(0);
}