首页 > 代码库 > atoi的实现

atoi的实现

处理策略完全模仿c语言的库函数

溢出处理策略:

输出上界或下界(2147483647和-2147483648)

测试数据:

char* s1 = "	\t\f\v\n\r-00100\n\t\f\v\n\r1234";
	char* s2 = "--099";
	char* s3 = "s100";
	char* s4 = "+2147483647sc";
	char* s5 = "20.0sc";
	char* s6 = "20-1sc";
	char* s7 = "0-099";
	char* s8 = "-9999999999999999999";//溢出
	char* s9 = "+9999999999999999999";

处理结果:

第一行为库函数结果,第二行为My_atoi结果




代码实现:

#pragma once
#include<iostream>
using namespace std;

int My_atoi(const char* pstr)//指针指向的内容不能变,指针不能变应是char* const pstr
{
	if (!pstr)
	{
		printf("Pointer is NULL\n");
		return 0;
	}
	unsigned int result = 0;//用unsigned便于溢出处理
	int sign = 1;//标志符号,默认为正
	int out = false;//aoti()要求第一个数字或符号与最后一个数字或符号间只能是数字,当遇到第一个数字或符号后,out=true,再遇到非数字退出
	while (*pstr)
	{
		if (*pstr > '9' || *pstr < '0')//开始转换后遇到非数字就返回
			if (out)
				return result*sign;
		if (*pstr == '-')
		{
			sign = -1;
			out = true;
		}
		else if (*pstr == '+')
			out = true;
		else if (*pstr <= '9' && *pstr >= '0')
		{
			result = result * 10 + *pstr - '0';
			//溢出时返回上下界
			if (result >= 2147483647 && sign == 1)
				return 2147483647;
			if (result >= 2147483648 && sign == -1)
				//若写成result*sign > 2147483648,会自动将2147483648的二进制表示(无符号的),
				//与int比较就将该表示转化为有符号整数100000...即 -2147483648,所以此处应用unsigned int
				//若用int则2147483648变为-2147483648比较,其次int最大2147483647,就算不变也不对
				return -2147483647 - 1;//不能写成-2147483648
			out = true;
		}
		else if (*pstr != ' ' && *pstr != '\n' && *pstr != '\r'
			&&*pstr != '\t'&&*pstr != '\v'&&*pstr != '\f')//这些个与空格等价
			return result*sign;
		pstr++;
	}
	return result*sign;
}

void main()
{
	char* s1 = "	\t\f\v\n\r-00100\n\t\f\v\n\r1234";
	char* s2 = "--099";
	char* s3 = "s100";
	char* s4 = "+2147483647sc";
	char* s5 = "20.0sc";
	char* s6 = "20-1sc";
	char* s7 = "0-099";
	char* s8 = "-9999999999999999999";//溢出
	char* s9 = "+9999999999999999999";

	int i1 = atoi(s1);
	int i2 = atoi(s2);
	int i3 = atoi(s3);
	int i4 = atoi(s4);
	int i5 = atoi(s5);
	int i6 = atoi(s6);
	int i7 = atoi(s7);
	int i8 = atoi(s8);
	int i9 = atoi(s9);

	cout << i1 << ' ' << i2 << ' ' << i3 << ' ' << i4 << ' '
		<< i5 << ' ' << i6 << ' ' << i7 << ' ' << i8 << ' ' << i9 << endl;

	i1 = My_atoi(s1);
	i2 = My_atoi(s2);
	i3 = My_atoi(s3);
	i4 = My_atoi(s4);
	i5 = My_atoi(s5);
	i6 = My_atoi(s6);
	i7 = My_atoi(s7);
	i8 = My_atoi(s8);
	i9 = My_atoi(s9);

	cout << i1 << ' ' << i2 << ' ' << i3 << ' ' << i4 << ' '
		<< i5 << ' ' << i6 << ' ' << i7 << ' ' << i8 << ' ' << i9 << endl;
	int a = 2147483648;
	cout << a << endl;//-2147483648
	system("pause");
}



atoi的实现