比较完整的字符串转换为整数

要考虑到各种情况,比如,正负数,特别大或特别小的,有不合法字符的。用一个全局变量标记输入是否合法,不要随便就return 0;测试了正数,负数,有字母,很大的数,很小的数,空串6中情况

#include<iostream>
using namespace std;
enum Status{Valid,Invalid};
int g_Status = Valid;//用一个全局变量来标记是不是遇到了非法输入

long long StrToIntCore(const char* digit, bool minus)
{
	long long num = 0;
	while(*digit != '\0')
	{
		if(*digit >= '0'&&*digit <= '9')
		{
			int flag = minus ? -1 : 1;
			num = num * 10 + flag*(*digit - '0');
			if((!minus && num > 0x7FFFFFFF) || (minus&&num < (signed int)0x80000000))//判断有没有超过范围
			{
				num = 0;
				break;
			}
			digit++;
		}
		else//字符串里有不合法的字符
		{
			num = 0;
			break;
		}
	}
	//正常结束
	if(*digit == '\0')
	{
		g_Status = Valid;
	}
	return num;
}


int StrToInt(const char* str)
{
	g_Status = Invalid;
	long long num = 0;
	if(str != nullptr && *str != '\0')
	{
		bool minus = false;
		if(*str == '+')
			str++;
		else if(*str == '-')
		{
			minus = true;
			str++;
		}
		if(*str != '\0')
		{
			num = StrToIntCore(str, minus);
		}
	}
	return (int)num;
}

int main()
{
	char* test1 = "+1234543";
	int t1 = StrToInt(test1);
	if(g_Status == 0)
		cout << t1 << endl;
	else
		cout << "输入非法" << endl;

	char* test2 = "-234651";
	int t2 = StrToInt(test2);
	if(g_Status == 0)
		cout << t2 << endl;
	else
		cout << "输入非法" << endl;

	char* test3 = "-2a3451";
	int t3 = StrToInt(test3);
	if(g_Status == 0)
		cout << t3 << endl;
	else
		cout << "输入非法" << endl;

	char* test4 = "6662112312313212313";
	int t4 = StrToInt(test4);
	if(g_Status == 0)
		cout << t4 << endl;
	else
		cout << "输入非法" << endl;

	char* test5 = "-66621113212313";
	int t5 = StrToInt(test5);
	if(g_Status == 0)
		cout << t5 << endl;
	else
		cout << "输入非法" << endl;

	char* test6 = "";
	int t6 = StrToInt(test6);
	if(g_Status == 0)
		cout << t6 << endl;
	else
		cout << "输入非法" << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值