自己实现了一个atoi函数,没有用到任何的库函数:
欢迎大家发表意见。
const int INT_MAX_MY = 0x7fffffff;
const int INT_MIN_MY = 0x80000000;
// Parse a string to a integer.
int atoi(char *str)
{
char *pCur = str;
int m;
// Locate the first character because there maybe spaces.
while(' ' == (*pCur))
++pCur;
// Resolve the first character.
char cStart = *pCur;
if(cStart >= '0' && cStart <= '9')
m = 1;
else
{
if('+' == cStart)
m = 1;
else if('-' == cStart)
m = -1;
else
return -1;
++pCur;
}
// Store the number of numeric characters in a variable.
int num = 0;
// Traverse the string.
while(*pCur)
{
if((*pCur) >= '0' && (*pCur) <= '9')
{
++num;
++pCur;
}
else
{
if('.' == (*pCur))
break;
else if(' ' == (*pCur))
{
++pCur;
continue;
}
else
return -1;
}
}
// Compute the integer.
int result = 0;
for(int i = 0; i < num; ++i)
{
// Skip the sapces.
while(' ' == *(--pCur));
int temp = m * ((*pCur) - '0');
if(0 == i)
result = temp;
else
{
if(m >0)
{
// determine whether the number overflows.
if((INT_MAX_MY - temp)>= result )
result += temp;
else
return -1;
}
else
{
if((INT_MIN_MY - temp)<= result)
result += temp;
else
return -1;
}
}
m *= 10;
}
return result;
}