面试题目:c语言的数字字符串转换为整数

//题目:c语言的数字字符串转换为整数
#include<stdio.h>
#define INT_MAX    0x7FFFFFFF
#define INT_MIN    (-0x7FFFFFFF-1)

/*
约束:
0. 参数中const变量指针使用;
1. 空指针处理;
2. 字符串前面空格处理;
3. 字符串正负号处理;
4. 字符前面 0 字符的处理;
5. 错误字符输入处理
6. 最大正数和最大负数溢出处理;
*/

/*将字符串转化为整数*/
int my_atoi(const char *buf) //0. 参数中const变量指针使用;
{
	__int64  tmp_data = 0;
	char i=0;
	signed char sign = 1;
	
	printf("输入字符串为:%s\r\n", buf);
	
	/*1. 空指针,返回*/
	if(NULL == buf)
	{
		printf("错误提示err:空指针\r\n");
		return 0;
	}
	
	/*2. 跳过字符串前面空格*/
	while(' ' == *buf)
	{
		buf++;
	}

	/*3.字符串正负号,负号显示,正号不显示*/
	if('-' == *buf) //负数
	{
		buf++;
		sign = -1;
	}
	else if('+' == *buf) //带符号的正数
	{
		buf++;
		sign = 1;
	}
	else //没带符号的正数
	{
		sign = 1;
	}

    /*4. 跳过字符前面 0 字符*/
	while('0' == *buf)
	{
		buf++;
	}
	
	/*开始遍历字符串*/
	while('\0' != *buf)
	{
		if(*buf >= '0' && *buf <= '9')
		{
			tmp_data *= 10;
			tmp_data += *(buf++)-'0';		 //tmp_data = tmp_data*10+(buf[i++]-'0'); 表示方法2.
		}
		else
		{ 
			/*5. 非法数据,返回0,不处理这包数据*/
			printf("错误提示err:非法输入\r\n");
			return 0;
		}
       		
	}

	tmp_data *= sign;
	
	/*6. 限制最大正数和最大负数溢出*/
	if((1 == sign) && (tmp_data > INT_MAX)) //0x7FFFFFFF
	{
		printf("错误提示err:正数溢出(需小于2147483647)\r\n");
		return 0; 
	}
	
	if((-1 == sign) && (tmp_data < (int)-2147483648)) //if((-1 == sign) && (tmp_data < INT_MAX) 
	{
		printf("错误提示err:负数溢出(需大于-2147483648)\r\n");
		return 0; 
	}
	
	return 	tmp_data;
}

/*主函数*/
void main(void)
{
	printf("字符串转整数:\r\n");
	
	printf("data: %d\r\n",my_atoi(" 1234"));
	printf("data: %d\r\n",my_atoi(NULL));
	printf("data: %d\r\n",my_atoi("  +1234"));
	printf("data: %d\r\n",my_atoi("  -4568"));
	printf("data: %d\r\n",my_atoi("  2147483647"));
	printf("data: %d\r\n",my_atoi("  -2147483648"));
	printf("data: %d\r\n",my_atoi("  2147483648"));
	printf("data: %d\r\n",my_atoi("  -2147483649"));
}

写的好的博客:

https://wizardforcel.gitbooks.io/the-art-of-programming-by-july/content/01.03.html

http://wuchong.me/blog/2014/03/17/string-to-int/

猜你喜欢

转载自blog.csdn.net/happygrilclh/article/details/106220053
今日推荐