模擬實現庫函數atoi,將字符串轉換成數字。
庫函數atoi函數原型:int atoi(const char *str );
該函數在平時我們經常應用,但對該函數內部的一些判斷缺少深刻的了解。
如果我們直接按最基本的功能完成此函數則代碼如下(沒有任何錯誤判斷):
int my_atoi(const char* str){ long long num = 0; while (*str != '/0') { num = num * 10 + (*str - '0'); str++; } return (int)num; }此函數能完成如“1234”這類字符串的轉換,但是若輸入“-1234”便不能識別。缺點: 1、不能判斷正負;
2、不能越過空格;
3、若返回0,不能分清是非法字符還是字符串本身是0;
4、沒判斷參數字符指針是否合法。
所以我們要解決以上的缺點,需要修改和優化并得到以下代碼:
#include<stdio.h>#include<stdlib.h>#include<ctype.h>enum START{ KVALID, //0 合法 KINVALID //1 非法};enum START start = KVALID; //定義全局變量,方便其他函數檢測狀態int my_atoi(const char* str){ start = KINVALID; long long num = 0; if (str != NULL && *str != '/0') { int flag = 1; //正負標志位 if (*str == '+') { str++; } else if (*str == '-') { str++; flag = -1; } while (*str != '/0') //循環到字符串結尾結束(正常退出) { if (isdigit(*str)) { num = num * 10 + flag * (*str - '0'); if (num > INT_MAX || num < INT_MIN) //判斷是否溢出(以整型為溢出標準) { num = 0; return (int)num; //此時返回0,且在非法狀態(溢出) } str++; } else if (isspace(*str)) { str++; //將空格跳過 } else { break; //若遇到0到9外的其他字符,跳出循環(非法狀態) } if (*str == '/0') { start = KVALID; //正常轉換完,狀態置成合法 } } } return (int)num; //此時返回0,狀態不確定}int main(){ char* str = "- 012@3"; int x = my_atoi(str); PRintf("%d/n",x); return 0;}輸出結果:
新聞熱點
疑難解答