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

I have a list of numbers that looks like this: 1.234D+1or 1.234D-02. I want to read the file using C. The function atofwill simply ignore Dand translate only the mantissa.

The function fscanfwill not accept the format '%10.6e', because it expects Einstead Dexponentially.

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

So, how would you read a file with numbers, using Dinstead Efor scientific notation? Please note that I do not mean how to read the lines yourself, but rather how to convert them to float.

Thank.

+1
source share
3 answers

You can use 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\n";
    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\n", d);
        }
    }
    return 0;
}

Conclusion:

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

replace D with E by going along the line. then atof.

+1
source

"D" "E" "D".

std::string dToE(string cppstr)
{
    str1.replace(cppstr.find("D"),1,"E");
    return cppstr;
}

If string C for scientific notation is defined: char * cstr = "1.2D + 03"; or usually obtained by a method strtokthat returns the string C, then use atof(dToE(string(cstr)).c_str())to get scientific notation with "E".

Since it atofonly accepts a C style string, you should use the c_str()string method to convert a C ++ string to a C string.

0
source

All Articles