在没有外部函数的情况下重现atoi()

时间:2018-03-03 11:59:59

标签: c char int data-conversion atoi

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

6 个答案:

答案 0 :(得分:3)

考虑到您的系统使用atoiASCII的实现会是这样的(请记住,这个数字也可能是负数)

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;
}

答案 1 :(得分:3)

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

#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] != '\0') {
    // 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

答案 2 :(得分:2)

尝试使用参考页中的代码: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] != '\0'; ++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;
}

答案 3 :(得分:1)

您可以转换charchar*,如下所示:

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

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

答案 4 :(得分:0)

直接来自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;
}

答案 5 :(得分:0)

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

#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