一个精简版本:
#include <ctype.h>
int my_atoi(const char* p)
{
assert(p != NULL);
bool neg_flag = false;// 符号标记
int res = 0;// 结果
if(p[0] == '+' || p[0] == '-')
neg_flag = (*p++ != '+');
while(isdigit(*p)) res = res*10 + (*p++ - '0');
return neg_flag ?0 -res : res;
}
long strtoint(char *str,int length)
{
if(length > 1)
return str[0]=='-' ? strtoint(str, length-1)*10-(str[length-1]-'0') : strtoint(str, length-1)*10+str[length-1]-'0';
else
return str[0]=='-' ? 0 : str[0]-'0';
}
一个较完善的版本:
#include <iostream>
#include <cctype>
#include <cassert>
using namespace std;
#define MAX_INT ((unsigned)(-1) >> 1)
//#define MIN_INT (MAX_INT + 1)
int Str2Int(const char* pStr)
{
assert( pStr != NULL );
bool negFlag=false;
int ret=0;
if (pStr[0]=='+' || pStr[0]=='-')
negFlag=(*(pStr++) != '+');
bool flag=true;
while(flag)
{
if(isdigit(*pStr))
{
if (!negFlag)
{
if ( ret*10.0 > MAX_INT -(*(pStr)-'0'))
{
cout<< "Overflow!"<<endl;
assert(false);
}
}
else
{
if ( ret*10.0 >MAX_INT -(*(pStr)-'0')+1 )
{
cout<< "Underflow!"<<endl;
assert(false);
}
}
ret= ret*10 + (*(pStr++)-'0');
}
else
{
if (*pStr== '.' || *pStr== '\0')
flag=false;
else
{
cout<< "Illegal character!"<<endl;
assert(false);
}
}
}
return negFlag==true ? (-ret): ret;
}
int main()
{
char a[10]="-123.4";
cout<<Str2Int(a)<<endl;
char *b="1234";
cout<<Str2Int(b)<<endl;
char *d="2147483647";
cout<<Str2Int(d)<<endl;
char *e="-2147483648";
cout<<Str2Int(e)<<endl;
char *f="-2147483649";
cout<<Str2Int(f)<<endl;
char *g="2147483648";
cout<<Str2Int(g)<<endl;
char *c=NULL;
cout<<Str2Int(c)<<endl;
return 0;
}
32位机 int型有符号整数的范围 -2147483648 ~ 2147483647