问题描述:
试编写程序实现字符串到整数的转换,例如输入字符串12345,输出整数12345.
思考中:
我们都知道在库函数中有一个函数atoi可以实现这个功能,那么我们先分析下库函数中的atoi。
所属头文件:#include<stdlib.h>
函数原型:int atoi( const char *string);
函数说明:参数*stringr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。否则,返回零。
要实现这个转换功能,我们需要模拟实现atoi,在模拟过程中我们要用到两个标准库函数:
1.isspace:所属头文件为<ctype.h>,
函数原型为:
int isspace( int c );
2.isdigit:
所属头文件为<ctype.h>,
函数原型为:
int isdigit( int c );
在以下代码实现中会提及他们各自的功能。
代码实现:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<ctype.h>
#define INT_MAX 2147483647
#define INT_MIN -2147483647
enum STATE
{
VALID,
INVALID
};
enum STATE state = INVALID;//state置为1
int my_atoi(char *str)
{
int flag=0;
long long ret=0;
assert(str);
state=INVALID;
while(isspace(*str))//处理空格
{
str++;
}
while(*str=='\0')
{
return 0;
}
if(*str=='+')//正数处理
{
str++;
}
else if(*str=='-')//负数处理
{
flag=-1;
str++;
}
while(isdigit(*str))//检查参数*str是否为阿拉伯数字0到9。
{
ret=ret*10+flag*(*str-'0');
if((ret>INT_MAX)||(ret<INT_MIN))
{
return 0;
}
str++;
}
if(*str=='\0')//正常结束
{
return (int)ret;
}
else//处理异常
return ret;
}
int main()
{
char *p=" -12345";
int ret=my_atoi(p);
printf("%d\n",ret);
system("pause");
return 0;
}
运行结果: