gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:28:14 25 4
gpt4 key购买 nike

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

最佳答案

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

#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

关于c - 在没有外部函数的情况下复制 atoi(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49083861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com