码迷,mamicode.com
首页 > 其他好文 > 详细

字符串转换成整数

时间:2016-01-04 13:15:24      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

参考自:http://taop.marchtea.com/01.03.html

下面是我实现的代码,如有不妥之处,望指正,谢谢!

#include <stdio.h>

const int INT_MAX = (int)((unsigned)~0 >> 1);
const int INT_MIN = -(int)((unsigned)~0 >> 1) - 1;

int StrToInt(const char *str)
{
	if (str == NULL)
	{
		printf("The string is null!");
		exit(1);
	}
	int num = 0;
	if (str[0] != ‘-‘ && str[0] == ‘+‘ || (str[0] -‘0‘ <=9 && str[0] - ‘0‘ >=0))
	{
		for (int i = 0; str[i] != ‘\0‘; ++i)
		{
			if (str[i] - ‘0‘ <= 9 && str[i] - ‘0‘ >= 0)
			{
				if (num > INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - ‘0‘) > INT_MAX % 10))
				{
					num = INT_MAX;
					break;
				}
				else{
					num *= 10;
					num += (str[i] - ‘0‘);
				}
			}
			else{
				printf("Having a wrong with input!");
				exit(1);
			}
		}
	}
	else if (str[0] == ‘-‘){
		for (int i = 1; str[i] != ‘\0‘; ++i)
		{
			if (str[i] - ‘0‘ <= 9 && str[i] - ‘0‘ >= 0)
			{
				if (num < INT_MIN / 10 || (num == INT_MIN / 10 && (str[i] - ‘0‘) > -(INT_MIN % 10)))
				{
					num = INT_MIN;
					break;
				}
				else{
					num *= 10;
					num -= (str[i] - ‘0‘);
				}
			}
			else{
				printf("Having a wrong with input!");
				exit(1);
			}
		}
	}
	else{
		printf("It‘s wrong!");
		exit(1);
	}
	return num;
}

 

字符串转换成整数

标签:

原文地址:http://www.cnblogs.com/mingbujian/p/5098344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!