字符串到实数转化

/*
  Name: 字符串到实数转化 
  Author: Unimen
  Date: 23/09/2011 09:53
*/

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

double myatof(char *str)
{
	int i;
	int sign; //控制符号 
	double pow = 1.0;
	double val = 0.0;
	//去掉前导空格 
	for (i=0; isspace(str[i]); ++i);
	sign = str[i]=='-' ? -1 : 1;
	if (str[i]=='+' || str[i]=='-')
		i++;
	//处理实数中的整数部分
	for (; isdigit(str[i]); ++i) 
		val = val * 10 + (str[i]-'0');
	if (str[i] ==  '.')
		++i;
	//处理小数部分
	for (; isdigit(str[i]); ++i)
	{
		val = val * 10 + (str[i]-'0');
		pow *= 10;
	} 
	return sign * val / pow;
}

int main()
{
	cout<<myatof("-10.586")<<endl;
	return 0;
}


你可能感兴趣的:(字符串到实数转化)