atoi函数实现

    xiaoxiao2022-06-30  64

    

    昨天被鄙视了了,一是会错意,二是代码写的相当难看。来,今天这个运行过 没问题

    #include<stdio.h> #include<stdlib.h> #include<string.h>

    #define INT_MAX ((int)0x7FFFFFFF) #define INT_MIN ((int)0x80000000) //#define INT_MAX (~(unsigned int)0/2)

    int valid = 1;

    int myatoi(const char * str) {     int  minus = 0;     long long result=0;     valid = 0;     if(str==NULL)//if str is NULL, return         return 0;     while(*str==' ')//the blank was ignored         str++;     if(*str=='-')//a minus number     {         minus = 1;         str++;     }     else if(*str=='+')//a positive number         str++;     if(*str<'0'||*str>'9')//if it is not a integer         return 0;

        valid = 1;//the following is valid value     while(*str>='0' && *str<='9')     {         result=result*10+*str-'0';         if((minus && result>INT_MAX + 1LL) || (!minus && result>INT_MAX))         {             valid = 0;             return 0;         }

            str++;     }         if(minus)         result*=-1;

        return (int)result; }

    int main(void) {     char const *a = "12345";     int value;     value= myatoi(a);     printf("value = %d\n",value);     return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-1126069.html

    最新回复(0)