#include <iostream>using namespace Std;Static intSflags =0;the//atof function is implemented. BOOL Isnum (CharCH) {return(CH-' 0 ') >=0|| (CH-' 0 ') <=9;} Float Getnum (Char*s,intFlags) {FloatCount=0;intk=0; while(*s! =' + ') {if(Isnum (*s) && *s!='. ')Count=Count*Ten+ *s-' 0 ';if((Isnum (*s) = =0&& *s! ='. ') || (Isnum (*s) = =0&& *s = ='. '&& k = =1)) {return 0; }if(*s = ='. ') {k++; }if(k >0) k++;if(k >7)return Count/1000000;//More than one. s++; } for(inti =0; I < K2; i++) {Count/=Ten; }return Count;} Float My_atof (Char*s) {FloatCount=0;intFlags =0;//Record the number of decimal places. if(s = = NULL) {sflags =1;return 0; } while(*s = ="') s++;if(*s = =' + ')return 0;if(*s = =' + ') {Count= Getnum (S +1, flags);return Count; }Else if(*s = ='-') {Count= Getnum (S +1, flags);return 0-Count; }Else{Count= Getnum (s, flags);return Count; }return 0;}intMain () {cout << my_atof (" -1.123456789") << Endl; cout << Atof (" -1.123456789") << Endl;}the implementation of//atoi. #include <iostream>using namespace Std;Static intFlags =0;intIsnum (CharCH) {return(CH-' 0 ') >=0|| (CH-' 0 ') <=9;}intGetnum (Char*s) {Long Long Count=0; while(*s! =' + ') {if(Isnum (*s)) {Count=Count*Ten+ *s-' 0 ';if(Count>=0x7fffffff)return 0x7fffffff; }if(*s = ='. ')return Count;if(Isnum (*s) = =0)return-1; s++; }return Count;}intMy_atoi (Char*s) {int Count=0;if(s = = NULL) {flags =1;return 0; }if(*s = =' + ')return 0; while(*s = ="') s++;if(*s = =' + ') {Count= Getnum (S +1);if(Count== -1)return 0;Else if(Count==0x7ffffffff) {return 0x7fffffff; }Else{return Count; } }Else if(*s = ='-') {Count= Getnum (S +1);if(Count== -1)return 0;Else if(Count==0x7fffffff) {return 0x7fffffff+1; }Else{return 0-Count; } }Else{Count= Getnum (s);if(Count== -1)return 0;return Count; }}intMain () {Char*s =New Char[ -]; Cin >> S; cout << My_atoi (s) << Endl;return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C++atoi and Atof