Trouble with reading floats from ascii file

I have had some very bad experiences with formatted read statements in other people’s code. The format statement puts a heavy (possibly undocumented) burden on the person who creates the input data to conform to very specific requirements on whitespace and number of digits for each input value. If you fail to match it, the program might silently read the wrong values and give you garbage output.

Here’s an example using formatted read where the input string doesn’t quite conform to the format specification:

character(len=24) :: inputstring = "1 23.45e6 7.89e10 1112"

read(inputstring,"(i3,1x,f6.2,1x,f6.2,1x,i3)") i,x,y,j

print *, i,x,y,j

end

Wildly incorrect output:

[bash: ~/scratch 5]$ gfortran formatted_read.f90 
[bash: ~/scratch 6]$ ./a.out 
          12   450000.000       8.89999974E+09         111

I worked on a help desk at Imperial College for several years and formatted input of real values was a common problem for users. E format was the major source of error.

External data Format Interpretation
136 e10.0 136.0
136 e10.4 0.0136
136 e10.10 0.0000000136
136.0 any of 136.0
the
above

Ian Chivers

1 Like