字符串转化为整形 AtoI函数

要求:遇到第一个非数字字符或者‘\n’ 就结束转化;异常条件就是int溢出,加以判断;开始判断时,跳过空格,tab,‘0’;遇到+-号时候,要注意保留字符位

#include<stdio.h>
#include<assert.h>

int AtoI(const char *p);

int main()
{

    char *str="21474836479";
    int str_turn=0;
    str_turn=AtoI(str);
    printf("%d\n",str_turn);
    return 0;

}

int AtoI(const char *p)
{
    assert( p!= NULL );

    long total=0;
    int flag=0;

    while( *p=='0' || *p==' ' || *p=='-'|| *p =='   ' || *p =='\n' || *p=='+' )
    {
        if( *p == '-')
            flag=1;

        p++;
    }

    while( *p > '0' && *p <='9')
    {
        total=total *10 + *p-'0';
        p++;
    }
    if(flag==1)
        total=-total;

    if(total > 2147483647 )   //防止溢出,用long来替代
        return 2147483647;
    if(total < -2147483648 )
        return -2147483648;

    return total;

}

猜你喜欢

转载自blog.csdn.net/caozhigang129/article/details/81060298