Skip to content

Function to format variable as string #435

Closed
@awvwgk

Description

@awvwgk

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    easyDifficulty level is easy and good for starting into this projectideaProposition of an idea and opening an issue to discuss ittopic: utilitiescontainers, strings, files, OS/environment integration, unit testing, assertions, logging, ...

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions