+ Reply to Thread
Results 1 to 3 of 3

Thread: Implement atof

  1. #1
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321

    Implement atof

    Write code to implement atof (string to float)

  2. #2
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321
    Code:
    double atof(char *s)
    {
            double a = 0.0;
            int e = 0;
            int c;
            while ((c = *s++) != '\0' && isdigit(c)) {
                    a = a*10.0 + (c - '0');
            }
            if (c == '.') {
                    while ((c = *s++) != '\0' && isdigit(c)) {
                            a = a*10.0 + (c - '0');
                            e = e-1;
                    }
            }
            if (c == 'e' || c == 'E') {
                    int sign = 1;
                    int i = 0;
                    c = *s++;
                    if (c == '+')
                            c = *s++;
                    else if (c == '-') {
                            c = *s++;
                            sign = -1;
                    }
                    while (isdigit(c)) {
                            i = i*10 + (c - '0');
                            c = *s++;
                    }
                    e += i*sign;
            }
            while (e > 0) {
                    a *= 10.0;
                    e--;
            }
            while (e < 0) {
                    a *= 0.1;
                    e++;
            }
            return a;
    }

  3. #3
    puspendra Guest
    #include<iostream>

    using namespace std;

    double atof( char *s)
    {
    int sign=1

    if(s == NULL)
    return 0;
    if( *s == '-')
    sign=-1;
    double out=0;
    while( s !=NULL || *s !='\0')
    {
    if(*s == ' ')
    continue;
    if(*s == '.')
    break;
    if( *s > '9' || *s < '0')
    return 0;
    out= out*10+(*s - '0');
    s++;
    }
    double decimalOut=0;
    int decCount=0;
    while( s != NULL && *s == '.')
    {
    if(*s == ' ')
    continue;
    if(*s == '\0')
    break;
    if( *s > '9' || *s < '0')
    return 0;
    decimal= decimal*10+(*s - '0');
    decimalCount++;
    }

    return sign*(out + (0.1 ^ decimalCount)*decimalcount);
    }

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts