int atoi(char str[])
{
int i,num=0;
for (i = 0; str[i] <= ‘9’ && str[i] >= ‘0’; i++)
{
/*
* 假设str[2]为‘9’
* ascll码表里面‘9’为0x39 ‘0’为0x30 相减为0x09 十以内的十进制与十六进制是一样的,十进制也就是9
*/
num = num * 10 + (str[i] – ‘0’);
}
return num;
}
//方案2能判断前面的空格和符号
int atoi(char str[])
{
int i, n, sign;
for (i = 0; isspace(str[i]); i++);
sign = (str[i] == ‘-‘) ? -1 : 1;
if (str[i] == ‘+’ || str[i] == ‘-‘)
i++;
for (n = 0; isdigit(str[i]); i++)
{
n = 10 * n + (str[i] – ‘0’);
}
return sign * n;
}