首页 > 代码库 > 【2014-11-19】字符串转化成整数

【2014-11-19】字符串转化成整数

int StrToInt(const char* str)
{
    long long num = 0;
    bool minus = false;

    if (str != NULL && *str != ‘\0‘)
    {
        if (*str == ‘+‘)
            str++;
        else if (*str == ‘-‘)
        {
            str++;
            minus = true;
        }
    }
    while (*str != ‘\0‘)
    {
        if (*str >= ‘0‘ && *str <= ‘9‘)
        {
            int flag = minus ? -1 : 1;
            num = num * 10 + flag * (*str - ‘0‘);
            if (minus && (num > 0x7FFFFFFF) || (!minus && num < (signed int)0x8000000))
            {
                num = 0;
                break;
            }
            str++;
        }
        else
        {
            num = 0;
            break;
        }
    }
    return num;
}

【2014-11-19】字符串转化成整数