【练习题】atoi和itoa函数的实现

int atoi (const char * str);   //Convert string to integer
char *  itoa ( int value, char * str, int base );  //Convert integer to string (non-standard function)
#include <stdio.h>
#include <ctype.h>

int my_atoi(const char *s)
{
	int i =0;
	int total = 0;
	int sign;

	while(isspace(*s)) //跳过空白符
		s++;

	sign = *s;
	if(*s == '+' || *s == '-') //跳过符号位
	{
		s++;
	}
	while(isdigit(*s))
	{
		total = 10*total + (*s - '0'); //将数字字符转换成整形数字
		s++;
	}

	if(sign == '-')
		return -total;
	else
		return total;
}

int main(void)
{
	char str[256];
	printf ("Enter your a numeric string: ");
	scanf("%s",str);
	printf("%d\n",my_atoi(str));
}
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

char *my_itoa(int value, char * str, int base)
{
	int sign,ch;
	int i,len;
	char *tmp = str;
	char c;
	unsigned uvalue;

	if(base > 36 || base <=1)
	{
		printf("Base is between 2 and 36\n");
		return 0;
	}

	sign = (base == 10 && value < 0);
	if(sign) //记录符号,使value为正数
		uvalue = -value;
	else
		uvalue = (unsigned)value;

	while(uvalue)
	{
		ch = uvalue%base;
		uvalue = uvalue/base;
		if(ch < 10)
			*tmp = ch + '0'; // 0-9 直接输出"0"-"9"
		else
			*tmp = ch - 10 + 'a'; // > 10 输出"a"-...
		tmp++;
	}
	if(sign)
		*tmp++ = '-';
	*tmp = '\0';

	//生成的数字是逆序的,所以要逆序输出
	len = strlen(str);
	for(i=0;i<len/2;i++)  //首尾交换,共计 len/2 次
	{
		c = str[i];
		str[i] = str[len-i-1];
		str[len-i-1] = c;
	}
	return str;
}

int main(void)
{
	int value,base;
	char str[100];
	while(1)
	{
		printf("please input a number and base:");
		scanf("%d %d",&value,&base);
		printf("my_itoa:%s\n",my_itoa(value,str,base));
		printf("itoa:%s\n",itoa(value,str,base));
	}
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值