1

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.

Escualo
  • 40,844
  • 23
  • 87
  • 135

3 Answers3

2

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\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;
}

Output:

E:\> cnv
1.234000e+001
1.234000e-002
5.000000e+000
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • I am disappointed that C lacks native support for reading scientific notation using `D` instead of `E`. Your proposed code is the closest to a perfect solution. Thanks! – Escualo Apr 01 '10 at 17:05
  • 3
    @Arrieta: I am disappointed it can't parse numbers where the letter Q appears instead of the numeral 0 (zero). Seems the library designers didn't understand how essential our requirements are for so many programs... ;-) – Tony Delroy Jun 22 '12 at 12:14
1

replace D with E, by looping along string. then atof.

Andrey
  • 59,039
  • 12
  • 119
  • 163
0

Here this function is to replace "D" into "E" in the scientific notation with "D".

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

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

Since atof only accept C style string, you should use c_str() string method to convert C++ string into C string.

Tong
  • 2,057
  • 2
  • 15
  • 20