模拟實作atoi,例如輸入字元串“12345”,輸出整數12345
我們需要考慮很多種情況,庫裡的atoi函數處理了各種情況,讀者可以試着調用一下
1. ''12345".輸出 12345 2."-12345'',輸出 -12345
3." 12345",輸出 12345 4.考慮溢出的情況
5.遇到非法字元傳回已計算到的值,程式結束。比如"a12345",輸出0. "12a345",輸出12. "12345a'',輸出"12345"
#include<stdio.h>
#include<iostream>
#include<assert.h>
#include<ctype.h>
#include<stdlib.h>
enum STATE
{
VALID, //合法
INVALID //非法
};
enum STATE state = INVALID;
int my_atoi(const char *str)
{
int flag = 1;
long long ret = 0;
//空指針
assert(str != NULL);
//空字元串的情況
if (*str == '\0')
{
return 0;
}
//處理空白字元
while (isspace(*str))
{
str++;
}
//處理+-号
if (*str == '+')
{
str++;
}
if (*str == '-')
{
str++;
flag = -flag;
}
while (*str)
{
if (isdigit(*str))
{
ret = ret * 10 + flag *(*str - '0');
//考慮溢出的情況
if ((ret > INT_MAX) || (ret<INT_MIN))
{
return (int)ret;
}
}
//非法字元
else
{
state = VALID;
return (int)ret;
}
str++;
}
state = VALID;
return (int)ret;
}
int main()
{
char *p = "-12345";
int ret = my_atoi(p);
if (state == VALID)
{
printf("%d\n", ret);
}
system("pause");
return 0;
}