天天看点

模拟实现C库里的itoa()函数和atoi()函数

一、函数原型

        两个函数都在C语言里的<stdlib.h>库函数里。

        int atoi(const char *nptr);将字符串转换为整型值。

     char* itoa(int vulue,char *str,int base)itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参是

转移数字时所用的基数。比如10表示十进制,二表示二进制。

二、模拟实现

1、atoi() C++实现:

#include<iostream>
using namespace std;
int Atoi(const char* str)
{
	int tmp=0;
	const char* ptr=str;//ptr保存str字符串开头
	if(*str=='-'||*str=='+')
	{
		str++;
	}
	while(*str!=0)
	{
		if((*str<'0')||(*str>'9'))
		{
			break;
		}
		tmp=tmp*10+(*str-'0');
		str++;
	}
	if(*ptr=='-')
	{
		tmp=-tmp;
	}
	return tmp;
}
int main()
{
	int n=0;
	char p[10]="";
	cin.getline(p,20);
	n=Atoi(p);
	cout<<n<<endl;
	return 0;
}
           

2、itoa()C语言实现:

#include <ctype.h>
#include <stdio.h>
void itoa (int n,char s[]);
int main(void )
{ 
	int n;
	char s[100];
	printf("Input n:");
	scanf("%d",&n);
	printf("the string : ");
	itoa (n,s);
	printf("\n");
	return 0;
}
void itoa (int n,char s[])
{
	int i,j,sign;
	if((sign=n)<0)//记录符号
	n=-n;//使n成为正数
	i=0;
	do
	{
		s[i++]=n%10+'0';//取下一个数字
	}
	while ((n/=10)>0);//删除该数字
	if(sign<0)
	s[i++]='-';
	s[i]='\0';
	for(j=i;j>=0;j--)//生成的数字是逆序的,所以要逆序输出
    printf("%c",s[j]);
}