// 字符串转换为整数,字符串可能包含:
// 1.开头和结尾可能有空格,
// 2.可能有+-号
// 3.可能有非法符号,这时结束转换
// 4.可能溢出,这时返回0
#include <iostream>
#include <assert.h>
#include <string.h>
using namespace std;
int str2Int(const char *str)
{
assert(str!= NULL);
int n=strlen(str);
const char *p1=str, *p2=str+n-1;
// dealing with space
while (isspace(*p1) && p1<=p2)
{
p1++;
}
while (isspace(*p2) && p1<=p2)
{
p2--;
}
//
int nSymbol=1;
if (p1[0]=='+')
{
nSymbol=1;
p1++;
}
else if (p1[0]=='-')
{
nSymbol=-1;
p1++;
}
else if (!isdigit(p1[0]))
{
return 0;
}
int sum=0;
while (p1<=p2)
{
if (!isdigit(p1[0]))
{
return sum*nSymbol;
}
sum = sum*10 + (unsigned char)(*p1 - '0');
if(sum<0)
{
cout<<"溢出!"<<endl;
return 0;
}
p1++;
}
return sum*nSymbol;
}
int main()
{
char str1[]="99999999999999999999999300";
char str2[]="-35.9 ";
char str3[]=" p300";
char str4[]=" 34d0 t";
cout<<str1<<" str2Int(): "<<str2Int(str1)<<" atoi: "<<atoi(str1)<<endl;
cout<<str2<<" str2Int(): "<<str2Int(str2)<<" atoi: "<<atoi(str2)<<endl;
cout<<str3<<" str2Int(): "<<str2Int(str3)<<" atoi: "<<atoi(str3)<<endl;
cout<<str4<<" str2Int(): "<<str2Int(str4)<<" atoi: "<<atoi(str4)<<endl;
return 0;
}