C: Any way to convert a text string to float, i.e. 1e100?

Unfortunately, in this journal I have some lines with this notation (1.00e4), I know that I can use printf with a specifier "%e"to create this notation, how would I read it?

Unfortunately strtof and scanf seem to return 0.00000 on "1e100", would I need to write my own parser for this?

(updated)

What I have as input:
line "4.1234567e5" or "4.5e5"

Required output:
float 412345.67 or integer "450,000"

+3
source share
3 answers

Start with this code:

#include <stdio.h>
int main (void) {
    double val;
    double val2 = 1e100;
    sscanf ("1e100", "%lf", &val);  // that an letter ELL, not a number WUN !
    printf ("%lf\n", val);          // so is that.
    printf ("%lf\n", val2);         // and that.
    return 0;
}

It outputs:

10000000000000000159028911097599180468360810000000000...
10000000000000000159028911097599180468360810000000000...

, 1 100 IEEE754. :

#include <stdio.h>

int main (int argc, char *argv[]) {
    double val;
    int i;
    for (i = 1; i < argc; i++) {
        sscanf (argv[i], "%lf", &val);
        printf ("   '%s' -> %e\n", argv[i], val);
    }
    return 0;
}

sample :

pax$ ./qq 4.1234567e5 4.5e5 3.47e10 3.47e-10
   '4.1234567e5' -> 4.123457e+05
   '4.5e5' -> 4.500000e+05
   '3.47e10' -> 3.470000e+10
   '3.47e-10' -> 3.470000e-10
+2

double atof( const char * str );
+3

This does not work if I use the float data type. Perhaps the problem is there.

0
source

Source: https://habr.com/ru/post/1792992/


All Articles