字符串转整数

来源:互联网 发布:淘宝的港版beats能买吗 编辑:程序博客网 时间:2024/06/05 16:32
//字符串转整数int StrToInt(const char* str){    static const int MAX_INT = (int)((unsigned)~0 >> 1);    static const int MIN_INT = -(int)((unsigned)~0 >> 1);    unsigned int n = 0;    //判断输入是否为空    if(str == NULL)        return 0;    //处理空格    while(isspace(*str))        ++str;    //处理正负    int sign = 1;    if(*str == '+' ||*str == '-')    {        if(*str == '-')            sign = -1;        ++str;    }    //确定是数字才执行循环    while(isdigit(*str))    {        //处理溢出        int c = *str - '0';        if(sign>0 && (n>MAX_INT/10 || (n == MAX_INT/10 && c >MAX_INT%10)))        //发生正溢出时,返回MAX_INT        {            n = MAX_INT;            break;        }        else if(sign<0 && (n>(unsigned)MIN_INT/10 ||             (n == (unsigned)MIN_INT/10 && c>(unsigned)MIN_INT%10)))            //发生负溢出时,返回MIN_INT        {            n = MIN_INT;            break;        }        //把之前得到的数字乘以10,再加上当前字符表示的数字        n = n * 10 + c;        ++str;    }    return sign>0 ? n:-n;}void FunTest(){    cout<<StrToInt("10522545459")<<endl;    cout<<StrToInt("-545459")<<endl;    cout<<StrToInt("122334")<<endl;}
0 0