其实几年前实现过一个面试题版本的,参考:浮点数字符串转换成浮点数实现。
最近因为某些原因又拿了出来,做了一些简单的修改,支持了前端空格处理,溢出检测等等,当然精度处理这个难度有点大,没有特殊处理。另外带E(e)的浮点数字符串也进行了处理。需要特别说明的时候,运行时库里面是有一个类似的转换函数的,写一写只是练练手而已。
头文件
/* -------------------------------------------------------------------------
// 文件名 : KString2Float.h
// 创建者 : magic
// 创建时间 : 2015/7/28 17:36:43
// 功能描述 :
//
// $Id: $
// -----------------------------------------------------------------------*/
#ifndef __KSTRING2FLOAT_H__
#define __KSTRING2FLOAT_H__
#include <float.h>
#include <windows.h>
// -------------------------------------------------------------------------
namespace NSUtil
{
// -------------------------------------------------------------------------
// 函数 : atofloat
// 功能 : 将一个字符串转换为浮点数
// 返回值 : float
// 参数 : const char* s
// 附注 :
// -------------------------------------------------------------------------
float atofloat(const char* s);
// -------------------------------------------------------------------------
// 函数 : wtofloat
// 功能 : 将一个宽字符串转换为浮点数
// 返回值 : float
// 参数 : const wchar_t* s
// 附注 :
// -------------------------------------------------------------------------
float wtofloat(const wchar_t* s);
// -------------------------------------------------------------------------
// 函数 : strtofloatT
// 功能 : 将一个字符串转换为浮点数
// 返回值 : float
// 参数 : const tchar* s
// 附注 :
// -------------------------------------------------------------------------
template<typename tchar>
float strtofloatT(const tchar* s)
{
// check
if (!s)
return 0.0f;
float fResult = 0.0f; // 存储结果
tchar c = 0;
// 整数部分
bool bNegative = false;
float fInteger = 0.0f;
// 小数部分
bool bDec = false;
float fDecimal = 0.0f;
float fDecPower = 0.1f;
// 指数部分
bool bMeetE = false;
bool bEInFirst = true; // e不能在最前面
bool bNegativeExponent = false;
unsigned int nIntegerExponent = 0;
float fExponentData = 1.0f;
c = *s++;
/* skip whitespace */
while (0x20 == c)
c = *s++;
// 进行首位判断,判断是否是负数
if (0x2d == c)
{
bNegative = true;
c = *s++;
}
else if (0x2b == c)
{
bNegative = false;
c = *s++;
}
while (0 != c)
{
if (bMeetE)
{
// 指数部分
if (c >= 0x30 && c <= 0x39)
{
nIntegerExponent = nIntegerExponent * 10 + c - 0x30;
}
else
{
break;
}
}
else
{
if (0x65 == c || 0x45 == c)
{
if (bEInFirst)
break;
// 确定指数的符号
c = *s;
if (0 == c)
break;
if (0x2d == c)
{
bNegativeExponent = true;
c = *s++;
}
else if (0x2b == c)
{
bNegativeExponent = false;
c = *s++;
}
bMeetE = true;
}
else if (bDec)
{
bEInFirst = false;
// 小数部分
if (c >= 0x30 && c <