atoi函数与itoa函数的简单实现

#include<iostream>
using namespace std;
int myatoi(const char*pstr)
{
	int total = 0;
	bool signal = false;
	if (pstr == nullptr)
	{
		cout << "error" << endl;
		return 0;
	}
	
	//跳过开头空格
	while (*pstr==' ')
	{
		++pstr;
	}
	//判断是否带符号
	if (*pstr == '-')
	{
		signal = true;
		++pstr;
	}
	if(*pstr == '+')
		++pstr;

	while (*pstr)
	{	
		if (*pstr >='0' && *pstr <= '9')
			total = total*10 + *pstr - '0';//计算求值字符串的值
		else if (*pstr != ' ')	//在求值字符串内若出现非空格非数字字符则直接停止计算返回当前值
			break;
			++pstr;
	}
	if (signal)
		total = -1 * total;
	return total;
}
void reversestr(char* pstr)
{
	if (pstr == nullptr)
		return;
	char* pBegin = pstr;
	char* pEnd = pstr;
	while (*pEnd)
	{
		++pEnd;
	}
	--pEnd;

	while (pEnd > pBegin)
	{
		*pBegin = *pBegin ^ *pEnd;
		*pEnd = *pBegin ^ *pEnd;
		*pBegin = *pBegin ^ *pEnd;

		++pBegin;
		--pEnd;
	}
}
const char* myitoa(int num)
{
	static char res[16]{};
	bool signal = false;
	//先转正数处理
	if (num < 0)
	{
		signal = true;
		num = -num;
	}
	int i = 0;
	while (num)//获得反序的字符串
	{
		res[i] = num % 10 + '0';
		num = num / 10;
		++i;
	}
	if (signal)//处理符号
	{
		int size = strlen(res);
		res[size] = '-';
	}
	reversestr(res);//反转反序字符串得到正确字符串
	return res;
}

int main()
{
	cout << myatoi("123")<<endl;
	cout << myatoi("-123") << endl;
	cout << myatoi(" -124") << endl;
	cout << myatoi(" - 125") << endl;
	cout << myatoi("1 26") << endl;
	cout << myatoi("- 1 27p") << endl;
	cout << myatoi("- 1-28p") << endl;
	cout << myatoi("12k7") << endl;
	cout << myatoi("   -j27") << endl;
	cout << myatoi("   j27") << endl;
	cout << myatoi("   +27") << endl;

	cout << myitoa(3200) << endl;
	cout << myitoa(-3200) << endl;
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值