Closed
Description
We can already format integer and logical variables to strings, but we don't have routines to write floating point values yet. Maybe we can implement a simple solution by wrapping the internal IO in a function as a separate module. The size of the buffer might be problematic since it can overflow in case a format specifier like '(10000x, g0)'
is passed.
The actual implementation is pretty straight-forward:
! SPDX-Identifier: MIT
#:include "common.fypp"
#:set KINDS_TYPES = REAL_KINDS_TYPES + INT_KINDS_TYPES + LOG_KINDS_TYPES
!> Routines for dealing with format specifiers
module stdlib_format
use stdlib_kinds, only : sp, dp, qp, int8, int16, int32, int64, lk, c_bool
implicit none
private
public :: format_string
!> Create a character string representing the value of the provided variable.
interface format_string
#:for type, kind in KINDS_TYPES
module procedure :: format_string_${type[0]}$${kind}$
#:endfor
end interface format_string
contains
#:for type, kind in KINDS_TYPES
!> Format ${type}$ variable as character sequence
pure function format_string_${type[0]}$${kind}$(val, format) result(string)
integer, parameter :: ik = ${kind}$
${type}$, intent(in) :: val
character(len=*), intent(in) :: format
character(len=:), allocatable :: string
integer, parameter :: buffer_len = 512
character(len=buffer_len) :: buffer
write(buffer, format, iostat=stat) val
if (stat == 0) then
string = trim(buffer)
else
string = "*"
end if
end function format_string_${type[0]}${kind}$
#:endfor
end module stdlib_format