首页 > 技术文章 > myatoi

area-h-p 2019-07-22 13:40 原文

atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数,应用在计算机程序和办公软件中。int atoi(const char *nptr) 函数会扫描参数 nptr字符串,会跳过前面的空白字符(例如空格,tab缩进)等。如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回0。特别注意,该函数要求被转换的字符串是按十进制数理解的。atoi输入的字符串对应数字存在大小限制(与int类型大小有关),若其过大可能报错-1。

实现思路:只需一次遍历,将其转化为十进制整型数据。首先定位字符串第一个非空格字符,检查其是否为“-”“+”号,若是,则确定其正负值。然后指针后跳,将字符转为整型(记得减去‘0’才是数字的真实值),乘10在加即可。

 

#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;

class Myatoi
{
	public:
		int func(const char* str);
};

int Myatoi::func(const char* str)
{
	if(strlen(str) == 0)
		return 0;
	int a = 0, flag = 1;

	while(str[0] == ' ')
		++str;

	if(str[0] == '-')
	{
		flag = -1;
		++str;
	}
	else if(str[0] == '+')
	{
		flag = 1;
		++str;
	}
	while(str[0]>='0' && str[0]<='9')
	{
		a *= 10;
		a += (int)(str[0] - '0');
		if(a > 0x80000000)
		{
			cout<<"Overflow!  ";
			return -1;
		}
		++str;
	}
	return flag*a;	

}


int main()
{
	char p[3][20] = {"-12345.678","+132342wr","999999999999999999"};
	
	Myatoi ai;
	for(int i=0; i<3; ++i)
	{
		cout<<"p["<<i<<"] = "<<p[i]<<"   myatoi(p["<<i<<"]) = "<<ai.func(p[i]);
		cout<<"  "<<atoi(p[i])<<endl;
	}
	return 0;
}

 结果如下

 

看起来在数字过大溢出时,标准atoi并没有正确报错-1。

推荐阅读