atof

简单的解析double字符串:

考虑的情况:

  1. 符号位
  2. 空格
  3. 异常输入(未考虑)
  4. 科学计数法(e,E)(未考虑)
#include <iostream>
#include <cmath>

using namespace std;

double atof_my(char* pStr){

	//跳过空格
	while(isspace(*pStr))
		++pStr;

	//处理符号位
	int sign = 1;
	if(*pStr == '-'){
		sign = -1;
		++pStr;
	}
	else if(*pStr == '+')
		++pStr;

	//转换整数部分
	double integer_part = 0.0;
	while(isdigit(*pStr)){
		integer_part = integer_part * 10 + *pStr - '0';
		++pStr;
	}
	if(*pStr == '.')
		++pStr;

	//转换小数部分
	double decimal_part = 0.0;
	int decimal_digit = 1;
	while(isdigit(*pStr)){
		decimal_part = decimal_part + (*pStr - '0')/pow(10, decimal_digit++);
		++pStr;
	}

	double res = integer_part + decimal_part;

	return sign * res;
}

int main(){
	char* s1 = "3.14";
	char* s2 = "-3.14";
	char* s3 = "+3.14";
	char* s4 = "    3.14";
	cout<<atof_my(s1)<<endl;
	cout<<atof_my(s2)<<endl;
	cout<<atof_my(s3)<<endl;
	cout<<atof_my(s4)<<endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40804971/article/details/82817228
今日推荐