There are two system functions in C + + that can implement string-to-float and string-to-shape, and implement these two functions below.
#include <iostream> #include <string>using namespace std;double atof (const char* s)//character type to float type {int i = 0;int k = 1;double d;double n = 0,m = 0;bool flag = true;if (*s = = '-')//processing symbol {flag = False;i + +;} Else{flag = true;} while (* (s + i)! = ' + ') {while (* (s + i) >= ' 0 ' && * (s + i) <= ' 9 ')//processing integer part {n = n * + (* (s + i)-' 0 '); i + + ;} I ++;while (* (s + i) >= ' 0 ' && * (s + i) <= ' 9 ')//processing fractional part {m = m * + (* (s + i)-' 0 '); k *= 10;i + +;}} if (flag) d = n + m/k; elsed =-1 * (n + m/k); return D;} int atoi (const char * s)//character shaping {int n = 0,i = 0;bool flag = true;if (*s = = '-')//processing symbol {flag = False;i + +;} Else{flag = true;} while (* (s + i)! = ' + ' && * (s + i) >= ' 0 ' && * (s + i) <= ' 9 ') {n = n * + (* (s + i)-' 0 '); i + +;} if (flag) n = N;elsen =-1 * n;return N;} int main (int argc, char *argv[]) {char S[10];char ss[10];int n;double d;cout<< "Input a string!" <<endl;cin>>s;cout<<atof (s) <<endl;cout<< "Input Another string!"<<endl;cin>>ss;cout<<atoi (ss) <<endl;return 0;}
Operation Result:
Implementation of Atof function in C + + and implementation of Atoi