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

要考虑到各种情况,比如,正负数,特别大或特别小的,有不合法字符的。用一个全局变量标记输入是否合法,不要随便就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;
}

猜你喜欢

转载自blog.csdn.net/qq_22080999/article/details/81393734