目的:編寫一個字元串轉整型的接口
/**************************************
* 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;
輸出情況如下: