c语言模拟实现atoi

#include 
//
//空指针
//""
//空白字符
//+/-
//溢出
//
#include 
#include 

enum State
{
	VALID,
	INVALID
}state = INVALID;//默认表示非法

int my_atoi(const char* str)
{
	assert(str);
	if (*str == '\0')
	{
		return 0;
	}
	//跳过空白字符
	while (isspace(*str))
	{
		str++;
	}
	int flag = 1;
	if (*str == '+')
	{
		str++;
	}
	else if (*str == '-')
	{
		flag = -1;
		str++;
	}
	long long ret = 0;
	while (*str)
	{
		if (isdigit(*str))
		{
			ret = ret * 10 + flag * (*str - '0');
			if (ret > INT_MAX)
			{
				return INT_MAX;
			}
			else if (ret < INT_MIN)
			{
				return INT_MIN;
			}
		}
		else
		{
			return (int)ret;
		}
		str++;
	}
	
	state = VALID;
	return (int)ret;
}

int main()
{
	int ret = my_atoi("123411111111111111115");

	if (state == VALID)
		printf("%d\n", ret);
	else
		printf("非法字符串转换,%d\n", ret);

	return 0;
}


int main()
{
	long num = 0;
	FILE* fp = NULL;
	if ((fp = fopen("fname.dat", "r")) == NULL)
	{
		printf("Can’t open the file!");
		exit(0);
	}
	while (fgetc(fp) != EOF)
	{
		num++;
	}
	printf("num=%d\n", num);
	fclose(fp);
	return 0;
}

你可能感兴趣的:(c++,算法,c语言)