首页 > 编程语言 > 详细

【C语言】编写函数实现库函数atoi,把字符串转换成整形

时间:2015-07-04 11:16:46      阅读:224      评论:0      收藏:0      [点我收藏+]
//编写函数实现库函数atoi,把字符串转换成整形
#include <stdio.h>
#include <string.h>
int my_atoi(const char *src)
{
	int flag=1;
	int sum=0;
	while (*src)
	{
		if (*src == ' ')
			src++;
		else if (*src == '+')
		{
			src++;
			flag = 1;
		}
		else if(*src == '-')
		{
			src++;
			flag = -1;
		}
		else if(*src >= '0'&&*src <= '9')
		{
			sum = sum * 10 + (*src - '0');
			src++;
		}
		else
		{
			return 0;
		}
	}
	sum = sum*flag;
	return sum;
}
int main()
{
	printf("%d\n", my_atoi(" +12345"));
	printf("%d\n", my_atoi(" -12345"));
	printf("%d\n", my_atoi("+12345"));
	printf("%d\n", my_atoi("-12345"));
	printf("%d\n", my_atoi("123  45"));
	printf("%d\n", my_atoi("234  5"));
	printf("%d\n", my_atoi(""));
	printf("%d\n", my_atoi("123ab"));
	return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

【C语言】编写函数实现库函数atoi,把字符串转换成整形

原文:http://blog.csdn.net/doudouwa1234/article/details/46753479

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!