Linux C 實現atoi函數

目的:編寫一個字符串轉整型的接口

/**************************************
* Description   : 實現atoi函數的作用
* Editor        :  Donkey
* Date          :  2019-5-4 23:01
**************************************/

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

int myatoi(char* str)
{
        if(NULL == str)
        {   
                return 0;
        }   
        int flag = 1;//正負數的標誌位,如果是負數,最後乘-1.
    
        int s = 0;

        while(*str == ' ')
        {   
                //去除開頭空格
                str++;
        }

        if(*str == '+' || *str == '-')
        {
                if(*str == '-')
                {
                        flag = -1;
                }
                str++;
        }
        else if(*str < '0' || *str > '9')
        {
                s = 2147483647;
                return s;
        }

        while(*str != '\0' && *str >= '0' && *str < '9')
        {
                //主要部分,減掉'0'是爲了ASCII的碼轉爲數字
                s = s * 10 + *str - '0';
                str++;

        }
        return s*flag;
}


int main(int argc,char **argv)
{
        int num;
        char * str = "123";
        num = myatoi(str);
        printf("[%d %s] str = '%s' , num = %d\n",__LINE__,__FUNCTION__,str,num);

        char *str2 = "a123";
        num = myatoi(str2);
        printf("[%d %s] str2 = '%s' , num = %d\n",__LINE__,__FUNCTION__,str2,num);

        char *str3 = "1 23";
        num = myatoi(str3);
        printf("[%d %s] str3 = '%s' , num = %d\n",__LINE__,__FUNCTION__,str3,num);

        char *str4;
        num = myatoi(str4);
        printf("[%d %s] str4 = '%s' , num = %d\n",__LINE__,__FUNCTION__,str4,num);
        return 0;

 

 

輸出情況如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章