Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

Tip: a function can return a deferred-length character variable #36

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

You cannot write to an unallocated deferred-length (DL) character string, but you can create a function that allocates a DL string, writes to it, and then TRIMs it. One use is to convert an integer or real to a deferred length string of minimal size..

module to_string_mod
implicit none
interface to_string
   module procedure to_string_int,to_string_real
end interface to_string
contains
!
pure function to_string_int(i) result(str)
integer, intent(in) :: i
character (len=:), allocatable :: str
allocate (character (len=1000) :: str)
write (str,"(i0)") i
str = trim(str)
end function to_string_int
!
pure function to_string_real(x,fmt) result(str)
real, intent(in) :: x
character (len=*), intent(in), optional :: fmt 
character (len=:), allocatable :: str
allocate (character (len=1000) :: str)
if (present(fmt)) then
   write (str,fmt) x ! use specified format
else
   write (str,"(f0.6)") x ! use default format
end if
str = trim(str)
end function to_string_real
!
end module to_string_mod
!
program test_to_string
use to_string_mod, only: to_string
implicit none
print "(*(:,'''',a,'''',:,1x))", to_string(-123), &
  to_string(3.14),to_string(3.14,"(f0.2)")
! two consective quotes inside quotes treated 
! as single quote
end program test_to_string
! output:
! '-123' '3.140000' '3.14'