atoi很不好写,头都大了...# JobHunting - 待字闺中
O*i
1 楼
写了一个,要考虑的情况真多...
假定是16位整数,范围是-32768到+32767
bool my_atoi(const char* str, int16& num)
{
if (str == NULL || str[0] == '\0')
return false;
int i = 0;
bool IsNeg = (str[0] == '-')? true : false;
if (str[0] == '+' || str[0] == '-')
{
if (str[1] == '\0')
return false;
i = 1;
}
num = 0;
const int num_limit = 3276;
const int digit_limit = (IsNeg)? 8 : 7;
int digit = 0;
bool max_int_reached = false;
for (; str[i] != '\0'; i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
digit = str[i] - '0';
if (max_int_reached || num > num_limit)
return false;
else if (num == num_limit && digit > digit_limit)
return false;
else if (num == num_limit && digit == digit_limit)
max_int_reached = true;
else
num = num * 10 + digit;
}
else
return false;
}
if (max_int_reached)
num = (IsNeg)? -32768 : 32767;
else
num *= (IsNeg)? -1 : 1;
return true;
}
假定是16位整数,范围是-32768到+32767
bool my_atoi(const char* str, int16& num)
{
if (str == NULL || str[0] == '\0')
return false;
int i = 0;
bool IsNeg = (str[0] == '-')? true : false;
if (str[0] == '+' || str[0] == '-')
{
if (str[1] == '\0')
return false;
i = 1;
}
num = 0;
const int num_limit = 3276;
const int digit_limit = (IsNeg)? 8 : 7;
int digit = 0;
bool max_int_reached = false;
for (; str[i] != '\0'; i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
digit = str[i] - '0';
if (max_int_reached || num > num_limit)
return false;
else if (num == num_limit && digit > digit_limit)
return false;
else if (num == num_limit && digit == digit_limit)
max_int_reached = true;
else
num = num * 10 + digit;
}
else
return false;
}
if (max_int_reached)
num = (IsNeg)? -32768 : 32767;
else
num *= (IsNeg)? -1 : 1;
return true;
}