atof and atoi

#include <iostream>
#include <cstdlib>
#include <ctype.h>
using namespace std;


/*
 * @brief: 转换输入的字符串到长整形数
 *   过滤字符串开始的空格、+-号,逐个遍历数字字符,直到字符串末尾、
 *   非数字,也可以支持E(e)指数字符串
 * @input: nptr, const char*, 输入的字符串
 * @return: long   
 */
long myatoi(const char* nptr)
{
double dRet = 0;
if(!nptr)
return dRet;
int nVal1 = 0,nVal2 = 0;
int nSign = 1;
int i = 0;


// 过滤空格
for(; isspace(nptr[i]); ++i);


// 判断+-
if(nptr[i] == '-')
{
++i;
nSign =  -1;
}else if(nptr[i] == '+')
{
++i;
}


// e或者.之前的整数部分
for(; ::isdigit(nptr[i]); ++i)
{
nVal1 = nVal1 * 10 + (nptr[i] - '0');
}

if((nptr[i] == 'e') || (nptr[i] == 'E')) // 是e的情况
{
int nSign2 = (nptr[++i] == '-') ? -1 : 1;


// e-, e+,e
if( (nptr[i] == '-') || (nptr[i] == '+') )
++i;


for(; ::isdigit(nptr[i]); ++i)
{
nVal2 = nVal2 * 10 + (nptr[i] - '0');
}
if(nSign2 == 1)
{
dRet = nVal1 * ::pow(10.0,nVal2); 
}else{
dRet = nVal1 / ::pow(10.0,nVal2); 
}
}else{
dRet = nSign * nVal1;
}
return dRet;
}


/*
 * @brief: 转换输入的字符串到浮点型数
 *   过滤字符串开始的空格、+-号,逐个遍历数字字符,直到字符串末尾、
 *   非数字,也可以支持E(e)指数字符串
 * @input: nptr, const char*, 输入的字符串
 * @return: double   
 */
double myatof(const char* nptr)
{
double dRet = 0;
if(!nptr)
return dRet;
int nVal1 = 0,nVal2 = 0;
int nSign = 1;
int i = 0;


// 过滤空格
for(; isspace(nptr[i]); ++i);


// 判断+-
if(nptr[i] == '-')
{
++i;
nSign =  -1;
}else if(nptr[i] == '+')
{
++i;
}


// e或者.之前的整数部分
for(; ::isdigit(nptr[i]); ++i)
{
nVal1 = nVal1 * 10 + (nptr[i] - '0');
}


if(nptr[i] == '.') // 是.的情况
{
// .之后的整数部分
int num = 0;
for(++i; ::isdigit(nptr[i]); ++i)
{
nVal2 = nVal2 * 10 + (nptr[i] - '0');
++num;
}
dRet = nSign * (nVal1 + nVal2 /::pow(10.0,num) ); 
}else if((nptr[i] == 'e') || (nptr[i] == 'E')) // 是e的情况
{
int nSign2 = (nptr[++i] == '-') ? -1 : 1;


// e-, e+,e
if( (nptr[i] == '-') || (nptr[i] == '+') )
++i;


for(; ::isdigit(nptr[i]); ++i)
{
nVal2 = nVal2 * 10 + (nptr[i] - '0');
}
if(nSign2 == 1)
{
dRet = nVal1 * ::pow(10.0,nVal2); 
}else{
dRet = nVal1 / ::pow(10.0,nVal2); 
}
}else{
dRet = nVal1;
}
return dRet;
}






int main(void)
{
cout<<myatoi("-2.5678")<<endl;
cout<<myatoi("2.5678")<<endl;
cout<<myatof(" 2.5a678")<<endl;
cout<<myatoi("8e-1")<<endl;
cout<<myatoi("8E3")<<endl;


system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值