码迷,mamicode.com
首页 > 其他好文 > 详细

itoa atoi

时间:2014-07-25 00:10:54      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:os   io   for   re   c   ar   new   size   

#pragma once

#include <iostream>
#include <string>
using namespace std;

//itoa
//int ==> string
//10进制
string itoa(int nNum)
{
	int nSize = 128;
	char* pStr = new char[nSize];
	memset(pStr,0,nSize);
	char* pCurr = pStr;
	char* pBg = pCurr;
	if(nNum < 0)
	{
		*pCurr = ‘-‘;
		pCurr ++;
		nNum = 0 - nNum;
		pBg = pCurr;
	}

	while(nNum > 0)
	{
		*pCurr = nNum%10 + ‘0‘;
		pCurr ++;
		nNum = nNum/10;
	}
	pCurr --;

	//倒置
	for(int i=0;i<=(pCurr - pBg)/2;i++)
	{
		char cTmp = *(pBg + i);
		*(pBg + i) = *(pCurr - i);
		*(pCurr - i) = cTmp;
	}

	string str(pStr);
	delete pStr;
	return str;
}


//atoi
int atoi(const char* pStr,int nLen = 0)
{
	if(nLen == 0)
	{
		nLen = strlen(pStr);
	}
	int nValue = 0;
	int nSub = 1;
	int nEnd = 0;
	if(pStr[0] == ‘-‘)
	{
		nEnd = 1;
	}
	for(int i=nLen-1;i>=nEnd;i--)
	{
		nValue += (pStr[i] - ‘0‘)*nSub;
		nSub *= 10;
	}
	if(nEnd == 1)
	{
		nValue = 0- nValue;
	}
	return nValue;
}



itoa atoi,布布扣,bubuko.com

itoa atoi

标签:os   io   for   re   c   ar   new   size   

原文地址:http://my.oschina.net/u/659405/blog/294446

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!