Tuesday, 16 September 2008

Formatted Read Statements

This is not a very exciting problem or solution, but I shall post it anyway.
I was trying to read formatted data from a file like this:

0 9.99929445e-01
1 6.46409406e-05
2 3.80249651e-06
3 1.03999904e-06
4 4.24499610e-07
5 2.23999794e-07

I first tried the following:

integer :: myint(5)
real(kind = 10) :: myreal(5)

do i = 1,5
read(2,20) myint(i),myreal(i)
end do
20 format(I6,E15.8E3)

The I6 refers to the field width of the integer column. But alas, the output was this:

0 0.99992944E+001
1 0.64640941E+001
2 0.38024965E+001
3 0.10399990E+001
4 0.42449961E+001
5 0.22399979E+001

Oddly enough, everything was in order except that it would round powers from e-01 to e-09 up to E+001, and e-10 to e-19 became E+000 etc. Most odd. The solution was to change the format statement to skip the 2 blank spaces between the columns, which I had forgotten to do:

20 format(I6,2X,E15.8E3)

Simple really, but I don't know why it gives such a strange behaviour.

No comments: