一、
class CException
{
public:
CException(const char* str) : m_strErr(str) {}
string GetErrInfo() { return m_strErr; }
private:
std::string m_strErr;
};
int myatoi(const char* p)
{
assert(p);
int nFlg = 1;
if ('-' == *p)
nFlg = -1;
if ('-' == *p || '+' == *p)
p++;
if ('\0' == *p)
throw CException("Invalid expression");
int nRet = 0;
while('\0' != *p)
{
if (*p < '0' || *p > '9')
throw CException("Invalid character");
int nVal = *p - '0';
int nNew = nRet*10 + nFlg * nVal;
if (nRet != 0 && ((nNew & 0x80000000) != (nRet & 0x80000000)))
throw CException("Integer over flow");
nRet = nNew;
p++;
}
return nRet;
}
二、
int atoi (char* str)
{
assert(str);
assert(str[0]);
int result = 0;
int newResult = 0;
if (str[0] == '+')
return atoi(str + 1);
if (str[0] == '-')
return -1 * atoi(str + 1);
int i = 0;
while (str[i])
{
assert(str[i] >= '0' && str[i] <= '9');
newResult = (result << 1) + (result << 3) + str[i] - '0';
assert(newResult >= result);
result = newResult;
i++;
}
return result;
}