#include <stdio.h>
int StrToInteger(const char* str)
{
static const int MAX = (int)((unsigned)~0 >> 1);
static const int MIN = -(int)((unsigned)~0 >> 1) - 1;
int num = 0;
int sign = 1;
int ch;
while (isspace(*str))
++str;
if (*str == '+' || *str == '-')
{
if (*str == '-')
sign = -1;
++str;
}
// in case of overflow
while (isdigit(*str))
{
ch = *str - '0';
if (sign > 0 && (num > MAX/10 || (num == MAX/10 && ch >= MAX%10)))
{
num = MAX;
break;
}
else if (sign < 0 && (num > (unsigned)MIN/10 || (num == (unsigned)MIN/10 && ch > (unsigned)MIN%10)))
{
num = MIN;
break;
}
num = num * 10 + ch;
++str;
}
return sign > 0 ? num : -num;
}
int main()
{
char* str = " +12r31fewfe3ada";
printf("%d\n", StrToInteger(str));
return 0;
}
StrToInteger
最新推荐文章于 2021-01-18 13:42:04 发布