OVERFLOW的处理相当麻烦, 特别还要注意INT_MIN, INT_MAX的情况, 贴一个我修改了n
遍的代码:
int myatoi(const char* p)
{
assert(p);
//Judge signal
bool bNeg = false;
const char* pCur = p;
if(*pCur == '-' || *pCur == '+')
{
if (*pCur++ == '-')
bNeg = true;
}
//treat the rest as positive numeric number, so for negative number
//it is 2^31, and for positive number it is 2^31
unsigned int uLimit = bNeg ? 0x7FFFFFFF + 1 : 0x7FFFFFFF;
// The reson to use unsigned int rather than int is to deal with 2^31
unsigned int uRes = 0;
unsigned int uDummy = UINT_MAX/10; // used to judge overflow of unsigned
int
do
{
//Deals with illegal character
if (*pCur < '0' || *pCur > '9')
throw CException("Illegal character found");
//Get current digit
int nDigit = *pCur - '0';
//Detect the unsigned integer overflow
if (uRes > uDummy || (uRes == uDummy && nDigit > 6))
throw CException("Over flow detected");
//update uRes
uRes = uRes*10 + nDigit;
//Overflow situation if uRes isn't overflow
if (uRes > uLimit)
throw CException("Over flow detected");
pCur++;
}while (*pCur != 0); // WTF stupid error again, do while not while
return bNeg ? (int)(-uRes) : (int)(uRes);
}