# Atoi函数C语言实现

2016-12-02 12:52:56来源:网络收集作者:路过秋天人点击

Atoi函数实现

atoi解析+，-后的数字字符，一直到非数字字符停止

atoi实现
int myAtoi(char* str) {
int lenStr = 0;
int i = 0;
long long totalValue = 0;
int negative = 1;
char realValue[20];
if (str == NULL)
{
return 0;
}
lenStr = strlen(str);
for (i = 0; i{
if (isspace(str[i])) //delete space table
{
continue;
}
else
{
break;
}
}
//lenStr = lenStr - i;
for (; i{
if (str[i] == '-')//read +or digit
{
if (i + 1 {
if (str[i + 1] >= '0' &&str[i + 1] <= '9')
{
negative = -1;
i = i + 1;
}
else
return 0;
}
else
{
return 0;
}
break;
}
else if (str[i] == '+')
{
if (i + 1 {
if (str[i + 1] >= '0' &&str[i + 1] <= '9')
{
negative = 1;
i = i + 1;
}
else
return 0;
}
else
{
return 0;
}
break;
}
else if (str[i] >= '0' &&str[i] <= '9')
{
negative = 1;
break;
}
else
{
return 0;
}
}
for (; i{
if (str[i] >= '0'&&str[i] <= '9')
{
totalValue = totalValue * 10 + (str[i] - '0');
if (totalValue>2147483647)
{
return negative<0 ? negative*2147483648 : 2147483647;
}
}
else
break;
}
/*
if(negative ==1 && (totalValue>2147483647||lenStr>10))
{
return 2147483647;
}
else if(negative ==-1 && (totalValue>2147483648||lenStr>10))
{
return -2147483648;
}
*/
return negative*(int)totalValue;
}