面试题33:把字符串转换为整数

C语言的库函数atoi()的作用是将一个字符串转换为整数。写一个函数StrToInt,实现这一功能。

// 写一个函数StrToInt实现将字符串转换为整数的功能.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"
#include <iostream>
using namespace std;

//特殊情况:1.字符串为空指针或空串
//2.字符串中有非0到9的字符(负号,#,@,等等)
//特别需要注意的是:还要考虑溢出的问题。正整数最大值0x7FFFFFFF,负整数最小值0x80000000
//函数功能:将字符串str转换为整数, 由参数nInt接收整数值,若转换成功返回true,否则返回false
bool StrToInt(char *str, int &nInt)
{
	if (str == "")
	{
		cout << "空串!" << endl;	
		return false;
	}
	else if (str == NULL)
	{
		cout << "空指针!" << endl;
		return false;
	}
	else if ((strcmp(str, "+")==0) || (strcmp(str, "-")==0))
	{
		cout << "字符串输入无效!" << endl;
		return false;
	}
	else
	{
		char *p = str;
		bool isFirst = true;//标记是否为字符串的第一个字符
		bool hasMinus = false;//标记字符串的第一个字符是否为负号
		nInt = 0;

		while (*p != '')
		{
			if (isFirst && (*p)=='-')//有负号
			{
				hasMinus = true;
				p++;
				continue;
			}
			else if (isFirst && (*p)=='+')
			{
				p++;
				continue;
			}

			if ((*p) >='0' && (*p) <= '9')//当前字符为数字字符
			{
				nInt = nInt * 10 + (*p) - '0';	
				if ((!hasMinus && nInt>0x7FFFFFFF) || (hasMinus && nInt<(signed int)0x80000000))//注意此处(signed int)
				{
					cout << "字符串数值溢出,输入无效!" << endl;
					return false;
				}
				p++;
			}
			else//当前字符为非数字字符
			{
				cout << "字符串中包含有非数字的字符,不能转换为数字!" << endl;
				return false;
			}     
		}

		if (hasMinus)//字符串有负号
		{
			nInt = (-1) * nInt;
		}

		return true;  
	}   
}

int _tmain(int argc, _TCHAR* argv[])
{

int nTest1 = 100000000000000;
int nTest2 = -1000000000000000;
     if(nTest1 > 0x7FFFFFFF)
	 {
		 cout << "上溢!" << endl;
	 }

	 if (nTest2 < (signed int)0x80000000)
	 {
		 cout << "下溢!" << endl;
	 }
		

	int nInt = 0;
	char *str = NULL;
	if (StrToInt("123", nInt))
	{
		cout << nInt << endl;
	}

	if (StrToInt("", nInt))//空串
	{
		cout << nInt << endl;
	}

	if (StrToInt(str, nInt))//空指针
	{
		cout << nInt << endl;
	}

	if (StrToInt("-123", nInt))
	{
		cout << nInt << endl;
	}

	if (StrToInt("+123", nInt))
	{
		cout << nInt << endl;
	}

	if (StrToInt("-12#3@", nInt))
	{
		cout << nInt << endl;
	}

	if (StrToInt("0", nInt))
	{
		cout << nInt << endl;
	}

	if (StrToInt("+", nInt))
	{
		cout << nInt << endl;
	}

	if (StrToInt("100000000000000000000000000000000000000", nInt))
	{
		cout << nInt << endl;
	}

	if (StrToInt("-100000000000000000000000000000000000000", nInt))
	{
		cout << nInt << endl;
	}

	system("pause");
	return 0;
}

运行结果:


 说明:在判断上溢、下溢时出现错误!不知缘由,请大牛指正!


原文地址:https://www.cnblogs.com/pangblog/p/3297176.html