gpt4 book ai didi

c++ - atoi在C++中的实现

转载 作者:太空宇宙 更新时间:2023-11-04 15:02:24 24 4
gpt4 key购买 nike

给定this implementation C++ 中的 atoi

// A simple atoi() function
int myAtoi(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[] = "89789";
int val = myAtoi(str);
printf ("%d ", val);
return 0;
}

这条线究竟是怎么回事

res = res*10 + str[i] - '0';

将一串数字转换成整型值? (老实说,我对 C++ 相当生疏。)

最佳答案

标准要求字符集中的数字是连续的。这意味着您可以使用:

 str[i] - '0'

将字符的值转换成它的等效数值。

res * 10 部分是将运行总数中的数字向左洗牌,以便为您要插入的新数字腾出空间。

例如,如果您要将“123”传递给此函数,则在第一次循环迭代后 res 将为 1,然后为 12,最后是 123

关于c++ - atoi在C++中的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28919861/

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