atoi Function

public pure elemental function atoi(string) result(val)

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: string

Return Value integer(kind=int32)


Contents

Source Code


Source Code

pure elemental function atoi (string) result(val)    ! Convert STRING to an integer value
integer(kind=int32) :: val
character(len=*), intent(in) :: string
character(len=1)            :: c
integer                     :: i
integer                     :: j
integer                     :: ilen
logical                     :: neg

   val = 0
   neg=.false.
   i=0
   c=' '

   ilen=len(string)
   do i=1, ilen                               ! Pass over any leading spaces
      c = string(i:i)
      if (c  /=  ' ') exit
   enddo

   if (c  ==  '-') then                       ! check for +- as first digit
      neg = .true.
      i = i + 1
   elseif (c  ==  '+') then
      neg = .false.
      i = i + 1
   endif

   do j=i,ilen                                ! Continue as long as its a digit ...
      c = string(j:j)
      if (lge(c, '0') .and. lle(c, '9')) then
         val = 10*val + ichar(c)-48           ! Shift number over and add new digit
      else
         exit
      endif
   enddo

   if (neg) val = -val                        ! Negate the result if necessary

end function atoi