實現atoi()函數開始之前,測試了庫中的atoi()函數,發現庫中提供的atoi函數可以處理許多異常,下面就是庫中可以處理的異常:
1.指針爲NULL
2.空字符串
3.(+,-)號處理
4.遇到異常字符時的處理方式
5.溢出時處理,分爲兩部分:
1).上溢出,輸出上界
2).下溢出,輸出下界
那麼對這些異常進行處理就可以完成一個簡單atoi()函數了。
代碼實現:
/*My_Atoi.c*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
typedef enum Ret
{
VALID,
INVALID
}Ret;
Ret state = INVALID; //用來判斷異常的全局變量
int My_Atoi(const char* str)
{
int flag = 1; //正負
long long ret = 0; //返回值
assert(str);
if(str == NULL) //空指針
{
return (int)ret;
}
if(str == '\0') //空字符串
{
return (int)ret;
}
while(*str == ' ') //空白字符
{
str++;
}
if(str == '\0') //空白字符串
{
return (int)ret;
}
else if(*str == '+' || *str == '-')
{
if(*str == '-')
{
flag = -1;
}
str++;
}
while(*str)
{
if((*str <= '9') && (*str >= '0'))
{
state = VALID;
ret = ret * 10 + flag * (*str - '0');
str++;
if(ret > INT_MAX) //上溢出
{
state = INVALID;
printf("上溢出,");
return (int)INT_MAX;
}
if(ret < INT_MIN) //下溢出
{
state = INVALID;
printf("下溢出,");
return (int)INT_MIN;
}
}
else //異常字符
{
return (int)ret;
}
}
return (int)ret;
}
int main()
{
int ret = My_Atoi("");
//int ret = My_Atoi("1213");
//int ret = My_Atoi("-1213");
//int ret = My_Atoi("123aaa");
//int ret = My_Atoi("-111111111111111");
//int ret = My_Atoi("111111111111111");
if(state == INVALID)
{
printf("輸入非法!!\n");
}
printf("ret = %d\n", ret);
system("pause");
return 0;
}
部分測試結果:
/*My_Atoi("")*/
/*My_Atoi("-1213")*/
/*My_Atoi("111111111111111")*/
/*My_Atoi("123aaa")*/
在以後寫一個庫中已有的函數,先使用它,並測試它可以完成的事情,以及可以處理的異常,只要考慮到那些異常處理,那麼這些函數就可以很輕鬆搞定。
本文出自 “Pzd流川楓” 博客,請務必保留此出處http://xujiafan.blog.51cto.com/10778767/1757626