C语言实现atoi和atof函数


#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

int ato_i(char *p) {
    assert(p);
    int k = 0;
    int sign = 1;
    while (*p) {
        if (isdigit(*p)) {
            k = k * 10 + *p - '0';
        } else if (k == 0) {
            if (*p == '-' && sign == 1) {
                sign = sign * (-1);
            }
            p++;
            continue;
        } else break;

        p++;
    }

    return k * sign;
}

double ato_f(char *p) {
    double val, power;
    int sign, i;
    for (;isspace(*p) && *p != '\0'; p++) ;
    sign = (*p == '-') ? -1 : 1;
    if (*p == '-' && *p == '+') p++;
    for (val = 0.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
    } 

    if (*p == '.') p++;

    for (power = 1.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
        power *= 10;
    }

    return sign * val / power;
}

double ato_fe(char *p) {
    double val, val2, power;
    int sign, sign2, i;
    for (;isspace(*p) && *p != '\0'; p++) ;
    sign = (*p == '-') ? -1 : 1;
    if (*p == '-' && *p == '+') p++;
    for (val = 0.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
    } 

    if (*p == '.') p++;

    for (power = 1.0; isdigit(*p) && *p != '\0'; p++) {
        val = 10 * val + *p - '0';
        power *= 10;
    }

    if (tolower(*p) == 'e') p++;
    sign2 = (*p++ == '-') ? -1 : 1;
    for (val2 = 0.0; isdigit(*p) && *p != '\0'; p++) {
        val2 = 10 * val2 + *p - '0';
    }

    if (sign2 == -1)
        return sign * val / power / pow(10, val2);
    else 
        return sign * val * pow(10, val2) / power;
}

long ato_l(char *p) {

}

int main(int argc, char **argv) {
    char *p = "123";
    char *p1 = "-123";
    char *p2 = "12a3";
    char *p3 = "  123";
    printf("p is %s, and ato_i(p) = %d \n", p, ato_i(p));
    printf("p1 is %s, and ato_i(p1) = %d \n", p1, ato_i(p1));
    printf("p2 is %s, and ato_i(p2) = %d \n", p1, ato_i(p2));
    printf("p3 is %s, and ato_i(p3) = %d \n", p1, ato_i(p3));

    char *s = "123.45";
    char *s2 = "123.45e-2";
    double d = ato_f(s);
    double d2 = ato_fe(s2);

    printf("ato_f = %f \n", ato_f(s));
    printf("ato_fe = %f \n", ato_fe(s2));
    return 0;
}


结果输出:

p is 123, and ato_i(p) = 123 
p1 is -123, and ato_i(p1) = -123 
p2 is -123, and ato_i(p2) = 12 
p3 is -123, and ato_i(p3) = 123 
ato_f = 123.450000 
ato_fe = 1.234500 


你可能感兴趣的:(C语言实现atoi和atof函数)