Convert a string into an integer.
parse_integer
routine.
Added error checking.Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
character(kind=CK, len=*), | intent(in) | :: | str |
the string to convert to an integer |
||
integer(kind=IK), | intent(out) | :: | ival |
the integer value |
||
logical(kind=LK), | intent(out) | :: | status_ok |
true if there were no errors |
subroutine string_to_integer(str,ival,status_ok) implicit none character(kind=CK,len=*),intent(in) :: str !! the string to convert to an integer integer(IK),intent(out) :: ival !! the integer value logical(LK),intent(out) :: status_ok !! true if there were no errors character(kind=CDK,len=:),allocatable :: digits integer(IK) :: ndigits_digits,ndigits,ierr ! Compute how many digits we need to read ndigits = 2*len_trim(str) if (ndigits/=0) then ndigits_digits = nint(log10(real(ndigits)))+1 allocate(character(kind=CDK,len=ndigits_digits) :: digits) write(digits,'(I0)') ndigits !gfortran will have a runtime error with * edit descriptor here ! gfortran bug: '*' edit descriptor for ISO_10646 strings does bad stuff. read(str,'(I'//trim(digits)//')',iostat=ierr) ival !string to integer ! error check: status_ok = (ierr==0) else status_ok = .false. end if if (.not. status_ok) ival = 0_IK end subroutine string_to_integer