1. Read in Fortran output double precision data

Hi,

I need to read in a data file generated by Fortran with double precision scientific notation, i.e.,
0.93028594D+02
which is formatted as "D10.8" in Fortran, and I got two questions:

(1) What's the best way to do in C? I have tried:

float data;
scanf(fp, "%e", &data);

or "%g" etc. but none gives me the desired value.

(2) If I manually change the letter "D" to "E", the number before read-in is 0.93028594E+02 (though unlikely I'll do things this way) and use "%e", I get a read-in value of 93.028595. How to avoid such a changed value?

Many thanks!

hz

2. The value didn't change.
0.93028594D+02 = 0.93028594E+02 = 0.93028594 * 10^02 = 93.028595

D10.8 simply says make the field 10 characters wide, and put 8 of them after the decimal.

If you don't want to change the D to an E manually, you can first read a line or a number out of the file into a buffer. Next, you could use strchr to find the location of the letter 'D' in your input buffer and change that character to an 'E'. Then you can use sscanf to convert the string representation into a decimal:
Code:
double data;
char buf[20]; // I don't know an appropriate size for your data
char *c;

if (fgets(buf, sizeof(buf), fp) != NULL) {
c = strchr(buf, 'D');
if (c == NULL) {
// uh oh, there is no 'D' in the string
}
*c = 'E';
// buf now contains something like "0.93028594D+02"
if (sscanf(buf, "%e", &data) != 1) {
// we had an error parsing the number
}
}
That would work if your input file had one number per line. Otherwise, you would have to use scanf with the %s or %[] format string to grab just the contents of jone number on that line, then go through with the strchr and sscanf bit.

3. Thank you anduril462! Now it works and I have converted to all D+02's to E+02's in my data file.

I know 0.93028594D+02 is the same as 93.028595, but don't quite understand why the last digit is changed from 4 to 5.

4. Typo?

5. Most likely floating point inaccuracy. You're probably way out there near the limits of a float, meaning the computer does a tiny bit of rounding since you can't necessarily represent that number perfectly in binary. Try a double for more precision.