Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

string - Reading ASCII numbers using "D" instead of "E" for scientific notation using C

I have a list of numbers which looks like this: 1.234D+1 or 1.234D-02. I want to read the file using C. The function atof will merely ignore the D and translate only the mantissa.

The function fscanf will not accept the format '%10.6e' because it expects an E instead of a D in the exponent.

When I ran into this problem in Python, I gave up and merely used a string substitution before converting from string to float. But in C, I am sure there must be another way.

So, how would you read a file with numbers using D instead of E for scientific notation? Notice that I do not mean how to read the strings themselves, but rather how to convert them to floats.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can take advantage of strtod and strtok:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char in[] = "1.234D+1 ABCD 1.234D-02 5
";
    char *cursor;
    char *endp;
    for ( cursor = strtok(in, " "); cursor; cursor = strtok(NULL, " ")) {
        double d = strtod(cursor, &endp);
        if ( *endp == 'D' ) {
            *endp = 'e';
            d = strtod(cursor, &endp);
        }
        if ( endp != cursor ) {
            printf("%e
", d);
        }
    }
    return 0;
}

Output:

E:> cnv
1.234000e+001
1.234000e-002
5.000000e+000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...