Atof () function
Atof (): Double atof (const char * Str );
Function: converts a string to a floating point number.
STR: string to be converted.
Return Value: double value returned for each function. This value is generated by parsing the input character as a number. If the input cannot be converted to a value of this type, the return value is 0.0.
Function Description: atof () scans the nptr parameter string and skips the leading space character until conversion starts when a number or positive or negative sign is encountered, the conversion ends only when a non-number or string ends ('\ 0') and returns the result. The STR string can contain positive and negative numbers, decimal points, or E (e) to represent the exponential part.
#include<iostream>using namespace std;double atof_my(const char *str){double s=0.0;double d=10.0;int jishu=0;bool falg=false;while(*str==' '){str++;}if(*str=='-')//记录数字正负{falg=true;str++;}if(!(*str>='0'&&*str<='9'))//如果一开始非数字则退出,返回0.0return s;while(*str>='0'&&*str<='9'&&*str!='.')//计算小数点前整数部分{s=s*10.0+*str-'0';str++;}if(*str=='.')//以后为小树部分str++;while(*str>='0'&&*str<='9')//计算小数部分{s=s+(*str-'0')/d;d*=10.0;str++;}if(*str=='e'||*str=='E')//考虑科学计数法{str++;if(*str=='+'){str++;while(*str>='0'&&*str<='9'){jishu=jishu*10+*str-'0';str++;}while(jishu>0){s*=10;jishu--;}}if(*str=='-'){str++;while(*str>='0'&&*str<='9'){jishu=jishu*10+*str-'0';str++;}while(jishu>0){s/=10;jishu--;}}} return s*(falg?-1.0:1.0);}int main(){char *s1=" 123.456567567e-10";char *a1=" 123.456567567e-10";char *s2="1234567.235e+10";char *a2="1234567.235e+10";char *s3=" 123.45656\07567e-10";char *a3=" 123.45656\07567e-10";double sum_1=atof_my(s1);double sum1=atof(a1);double sum_2=atof_my(s2);double sum2=atof(a2);double sum_3=atof_my(s3);//遇到'\0'结束double sum3=atof(a3);cout<<"atof_my:"<<sum_1<<endl;cout<<"atof :"<<sum1<<endl;cout<<"atof_my:"<<sum_2<<endl;cout<<"atof :"<<sum2<<endl;cout<<"atof_my:"<<sum_3<<endl;cout<<"atof :"<<sum3<<endl;system("pause");return 0;}
Running result comparison diagram:
String function --- atof () function description and implementation (Full Version)