在没有外部函数的情况下复制 atoi()

Reproducing atoi() without external functions

我希望在不使用 strtonum() 等任何其他函数的情况下重现 atoi() 函数的行为。我真的不明白如何将 charchar * 转换为 int 而不是将其转换为 ASCII 值。我在 C 中这样做,有什么建议吗?

尝试使用参考页中的代码:Write your own atoi()

// A simple C program for implementation of atoi
#include <stdio.h>

// A simple atoi() function
int PersonalA2I(char *str)
{
    int res = 0; // Initialize result

    // Iterate through all characters of input string and
    // update result
    for (int i = 0; str[i] != '[=10=]'; ++i)
        res = res*10 + str[i] - '0';

    // return result.
    return res;
}

// Driver program to test above function
int main()
{
    char str[] = "123456";
    int val = PersonalA2I(str);
    printf ("%d ", val);
    return 0;
}

您可以按如下方式转换 charchar*

int myAtoi(char *str)
{
    int dec = 0, i=0;

    for (i = 0; str[i] != '[=10=]'; ++i)
        dec = dec*10 + str[i] - '0';
    return dec;
}

直接来自Brian W. Kernighan, Dennis M. Ritchie: The C Programming Language

/* atoi: convert s to integer */
int atoi(char s[])
{
    int i, n;
    n = 0;
    for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
    n = 10 * n + (s[i] - '0');
    return n;
}

考虑到您的系统使用 ASCIIatoi 的实现类似于(请记住该数字也可以是负数)

int catoi(const char *string)
{
    int res = 0;
    int sign = 1;
    if (*string == '-')
    {
        sign = -1;
        string++;
    }
    if (*string == '+') string++;

    while (*string >= '0' && *string <= '9')
    {
        res = res * 10 + (*string - '0')
        string++;
    }
    return (sign < 0) ? (-res) : res;
}

哇,我很慢。很多人回答...顺便说一句,这是我的标志检测的简单示例。如果遇到无效字符,它 returns 字符串的第一个解析部分:

#include <stdio.h>

int my_atoi(const char* input) {
  int accumulator = 0, // will contain the absolute value of the parsed number
      curr_val = 0, // the current digit parsed 
      sign = 1; // the sign of the returned number
  size_t i = 0; // an index for the iteration over the char array 

  // Let's check if there is a '-' in front of the number,
  // and change the final sign if it is '-'
  if (input[0] == '-') {
    sign = -1;
    i++;
  }
  // A '+' is also valid, but it will not change the value of
  // the sign. It is already +1!
  if (input[0] == '+')
    i++;

  // I think it is fair enough to iterate until we reach 
  // the null char...
  while (input[i] != '[=10=]') {
    // The char variable has already a "numeric"
    // representation, and it is known that '0'-'9'                                 
    // are consecutive. Thus by subtracting the
    // "offset" '0' we are reconstructing a 0-9
    // number that is then casted to int.
    curr_val = (int)(input[i] - '0'); 

    // If atoi finds a char that cannot be converted to a numeric 0-9
    // it returns the value parsed in the first portion of the string.
    // (thanks to Iharob Al Asimi for pointing this out)
    if (curr_val < 0 || curr_val > 9)
      return accumulator;

    // Let's store the last value parsed in the accumulator,
    // after a shift of the accumulator itself.
    accumulator = accumulator * 10 + curr_val;
    i++;
  } 

  return sign * accumulator;
}


int main () {
   char test1[] = "234";
   char test2[] = "+6543";
   char test3[] = "-1234";
   char test4[] = "9B123";

   int a = my_atoi(test1);
   int b = my_atoi(test2);
   int c = my_atoi(test3);
   int d = my_atoi(test4);

   printf("%d, %d, %d, %d\n", a, b, c, d);
   return 0;
}

它打印:

234, 6543, -1234, 9

另一个可以用于长 ASCII 字符串的小的:

#include <stdio.h> 

long long int my_atoi(const char *c)
{
    long long int value = 0;
    int sign = 1;
    if( *c == '+' || *c == '-' )
    {
        if( *c == '-' ) sign = -1;
        c++;
    }
    while (*c >= '0' && *c <= '9') // to detect digit == isdigit(*c))
    {
        value *= 10;
        value += (int) (*c-'0');
        c++;
    }
    return (value * sign);
}

int main () {
   char test1[] = "1234567890123456789";
   char test2[] = "+7654312345678901234";
   char test3[] = "-932112345678901234";
   char test4[] = "9A123123456789012";

   long long int a = my_atoi(test1);
   long long int b = my_atoi(test2);
   long long int c = my_atoi(test3);
   long long int d = my_atoi(test4);

   printf(" %lld\n %lld\n %lld\n %lld\n", a, b, c, d);
   return 0;
}

输出:

 1234567890123456789
 7654312345678901234
 -932112345678901234
 9