自己写一个atoi程序

最主要的是要考虑输入条件,程序写出来了远不是面试官的目的。各种异常情况的处理、边界条件的处理,才是面试官主要考察的内容。

我所能想到的测试用例有:

1,字符串内含有非法字符,非法字符的定义为0-9,- 之外的所有字符

2,字符串表示负数

3,字符串表示的整数溢出


以下是我写的myatoi和UT

#include <string.h>
int myatoi(const char* a);

void TestString(const char* str)
{
	printf("%s = %d\r\n", str, myatoi(str));    
}
void Test()
{
	const char* test[] = {"0", "0x1","-","01", "-1","1","123","1000000000","-1000000000","100000000000","-100000000000"};
	for(int i = 0; i < sizeof(test) / sizeof(const char*); i++)
	{
		TestString(test[i]);
	}
}

int myatoi(const char* a)
{
	if(a == NULL || strlen(a) == 0)
	{
		printf("empty string!\r\n");
		return 0;
	}

	int t = a[0];
	int i = 0;
	if(t > '9' || t < '0')
	{
		if(t != '-')
		{
			printf("illegal char!\r\n");
			return 0;
		}
		else if(strlen(a) < 2)
		{
			printf("illegal char!\r\n");
			return 0;
		}
		else
		{
			i = 1;
		}
	}

	for(; i < strlen(a); i++)
	{
		if((a[i] > '9' || a[i] < '0'))
		{
			printf("illegal char!\r\n");
			return 0;
		}
	}
	int sign = 1;
	int pos = 0;
	if(a[0] == '-')
	{
		sign = -1;
		pos++;
	}
	int n = 0;
	while(pos < strlen(a))
	{
		if(n * 10 / 10 != n)
		{
			printf("overflow!\r\n");
			return 0;
		}
		n = n * 10 + (a[pos++] - '0');
	}
	return n * sign;
}

写完了以后总觉得不爽,看了看cplusplus上对atoi函数的定义,感觉这个C函数的声明本身就有问题。异常条件下返回0,这种异常处理方式很容易导致客户程序员犯下很难debug到的错误。感觉如果定义为 bool atoi(const char* a, int& i)会比较稳定。


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值