代码题--C++-实现itoa

代码题--C++-实现itoa


代码如下:

#include<stdio.h>  
#include<stdlib.h>  
  
int atoi_my(const char *str)  
{  
    int s=0;  
    bool falg=false;  
      
    while(*str==' ')  
    {  
        str++;  
    }  
  
    if(*str=='-'||*str=='+')  
    {  
        if(*str=='-')  
        falg=true;  
        str++;  
    }  
  
    while(*str>='0'&&*str<='9')  
    {  
        s=s*10+*str-'0';  
        str++;  
        if(s<0)  
        {  
            s=2147483647;  
            break;  
        }  
    }  
    return s*(falg?-1:1);  
}  
  
int main()  
{  
    char *s1="333640";  
    char *s2="-12345";  
  
    int sum1=atoi(s1);  
    int sum_1=atoi_my(s1);  
  
    int sum2=atoi(s2);  
    int sum_2=atoi_my(s2);  
  
    printf("sum1=\t%d\n",sum1);
    printf("sum_1=\t%d\n",sum_1);
    
    printf("sum2=\t%d\n",sum2);
    printf("sum_2=\t%d\n",sum_2);
    
    return 0;  
}

猜你喜欢

转载自blog.csdn.net/qq_41103495/article/details/108775999