简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM