A safer Read call in Fortran 95


In Fortran, the validation process is a more painful procedure in comparison with other programming environments. In the following code, a much more safer version of the Read subroutine is called, named SafeReadInteger. The syntax and the definition of the function is shown in the following code segment:

program TestSafeRead
implicit none
integer(4) :: iValue

!call SafeReadInteger("Enter the number of cylinders", iValue, "Wrong stuff")
call SafeReadInteger("Enter the number of cylinders", iValue)
print '(A, I4)', "The entered number of cylinders is: ", iValue

contains
subroutine SafeReadInteger(promptMessage, outVariable, errorMessage)
character(*), intent(in) :: promptMessage, errorMessage
!the errorMessage is optional
optional :: errorMessage
integer(4), intent(out) :: outVariable
!local variable to receive the integer value
integer(4) :: iostatus

do
!print the promptMessage on the screen and
!retain the cursor position next to the text
write (*, '(2A)', advance='no') promptMessage, ": "
read(*, *, iostat=iostatus) outVariable
if(iostatus==0) then
exit !exit the block if no error occurs
else if(present(errorMessage)) then
print '(A)', errorMessage
else
print '(A)', "[Error] The entered value is not a valid integer."
endif
enddo
end subroutine
end program

There are two alternative syntaxes: one with an error message and one without. If the user does not include an error message then a default error message will appear on invalid input.

This subroutine is defined for integer output and may be altered to output variables of other intrinsic types too.


Comments

Zaak said…
It may be worthwhile to contemplate using the F2003 intrinsic module iso_fortran_env to explicitly read from stdin and write to stdout, and write to stderror if the function throws an error. Alternatively you could also pass in (possibly optional) IO units to read from/write to, if you're concerned about handling more exotic cases, like reading/writing to other devices or files.

Popular posts from this blog

Write Unicode text using VBA

Calling Fortran intrinsic functions from Visual Basic

Dictionary class extensions (CopyTo, Sort) (C#)