C语言模拟实现atoi函数

本文详细探讨了如何使用C语言来模拟实现atoi函数,将字符串转换为整数。通过解析字符、处理正负号、跳过空格等步骤,阐述了实现过程的关键点。
摘要由CSDN通过智能技术生成
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>

enum
{
	INVALUE,
	VALUE
};

int my_atoi(char *str)
{
	int tmp = 0;
	int flag = 1;
	int num = 0;
	//空指针
	assert(str != NULL);
    //空字符串
	if (*str == '\0')
	{
		return 0;
	}
	//空格处理
	while (isspace(*str))
	{
		str++;
	}
	//+  -
	if (*str == '-')
	{
		str++;
		flag = -1;
	}
	//异常字符处理
	while (isdigit(*str))
	{
	    tmp = tmp * 10 + (*str -'0')*flag;
		str++;
		//溢出处理
		if ((tmp > INT_MAX) || (tmp < INT_MIN))
		{
			num = INVALUE;
		}
		else
		{
			num = VALUE;
		}
	}
	return tmp;
}

int main()
{
	int a = my_atoi("");
	int b = my_atoi("   ");
	int c = my_atoi("1234");
	int d = my_atoi("-1234");
	int e = my_atoi("   1234");
	int f = my_atoi("iii1234");
	int g = my_atoi("122344443433232323234");
	int h = my_atoi("-12333333333333333333");
	
	printf("%d\n", a);
	printf("%d\n", b);
	printf("%d\n", c);
	printf("%d\n", d);
	printf("%d\n", e);
	printf("%d\n", f);
	printf("%d\n", g);
	printf("%d\n", h);
	system("pause:");
	return 0;
}

输出结果:



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值