atoi函数实现

int atoi(const char * str);

函数说明参考:

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

功能:将str里整数字符,翻成整数

该函数:1:忽略开始的空白字符串,知道非空白的字符开始转换

2:处理正负+ - 字符

3:如果字符串为空,或者字符串里首字符不为数字或者正负号,不做转换

 

Return Value

On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.

#include <stdio.h>
#include <iostream>
#define MIN_INT (-2147483648)
#define MIN_INT (2147483647)
using namespace std;
//转换,没有进行最大值检查
int myatoi(const char* str)
{
	int sign = 1;
	if (!str)return 0;
	int intvalue = 0;
	while (*str ==' ')str++;//找到第一个非空白字符
	if (*str == '-')//检查+-号
	{
		sign = -1;
		str++;
	}
	else if (*str == '+')
	{
		sign = 1;
		str++;
	}

	while(*str!='\n')
	{
		if (*str <='9'&&*str>='0')//是否为数字
		{
			intvalue = 10*intvalue + *str - '0';
			str++;
		}
		else break;
	}
	return intvalue*sign;
}
int main()
{
	char *s = "12345 6s78";
	char *s1 = "   3245609ac34";
	char *s2 = "s145553290";
	int m = atoi(s);
	int mym = myatoi(s);
	int m1 = atoi(s1);
	int mym1 = myatoi(s1);
	int m2 = atoi(s2);
	int mym2 = atoi(s2);
	cout<<m<<":"<<mym<<"&&"<<m1<<":"<<mym1<<"&&"<<m2<<":"<<mym2<<endl;
	system("pause");
	return 0;
}

  



 


posted @ 2012-04-19 16:00  foreverlearn  阅读(230)  评论(0编辑  收藏  举报