Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting arbitrary floating-point string to real in Fortran 95

Are there any easy ways of convertin an arbitrary floating-point string to a real number in fortran? Think of something like strtod? The problem with READ statement is that all floating-point formats edit descriptors require explicit widths. So far the best workaround I made is something like:

pure function strtod(s)
  real(kind=8) :: strtod
  character(len=*), intent(in) :: s
  character(len=32) :: fmt
  integer :: dot
  dot = index(s, ".")
  if(dot < 1) then
     write(fmt, '("(F",I0,".0)")'), len_trim(s)
  else
     write(fmt, '("(F",I0,".",I0,")")'), len_trim(s), len_trim(s)-dot
  end if
  read(s,fmt), strtod
end function strtod

But I'm wondering if I'm missing something and may be is there a better way to do that?

like image 209
abbot Avatar asked Nov 03 '22 10:11

abbot


1 Answers

I must be missing something. What's wrong with doing it with list directed?

[luser@cromer stackoverflow]$ cat char2.f90
Program char2

  Implicit None

  Integer, Parameter :: wp = Selected_real_kind( 12, 70 )

  Real( wp ) :: a

  Character( Len = 32 ) :: s

  s = '0.'
  Read( s, * ) a
  Write( *, * ) a

  s = '1e10'
  Read( s, * ) a
  Write( *, * ) a

End Program char2
[luser@cromer stackoverflow]$ nagfor -C=all -C=undefined char2.f90
NAG Fortran Compiler Release 5.3.1 pre-release(904)
[NAG Fortran Compiler normal termination]
[luser@cromer stackoverflow]$ ./a.out
   0.0000000000000000
   1.0000000000000000E+10
like image 124
Ian Bush Avatar answered Nov 09 '22 05:11

Ian Bush