Implementation of Atof function in C + + and implementation of Atoi

Source: Internet
Author: User

 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.