BaRud
BaRud

Reputation: 3230

checking input type in fortran read statement

I have put a check in error made in the input as:

integer :: lsp 
chksp:do 
write(*,*) "#Enter Number" 
read(*,*,iostat=istat)lsp 
if (istat==0) then 
  exit chksp 
else 
  write(*,*)"Number can only be integer. Re-enter!" 
end if 
end do chksp 

The problem is, it can detect error if a character value in enteres, instead of a numeric value; but it cannot detect error, if a real value is entered, instead of a integer.

Any way to force it detect integer only?

NB: May be problem with ifort; gfortran is happy with the code.

Upvotes: 0

Views: 6525

Answers (2)

Ian Bush
Ian Bush

Reputation: 7442

Something like the following?

    ian@ian-pc:~/test/stackoverflow$ cat read.f90
Program readit

  Integer :: val
  Integer :: iostat

  val = -9999

  Do

     Read( *, '( i20 )', iostat = iostat ) val

     If( iostat == 0 ) Then
        Write( *, * ) 'val = ', val
     Else
        Write( *, * ) 'oh dear!!'
     End If

  End Do

End Program readit
ian@ian-pc:~/test/stackoverflow$ nagfor -o read read.f90
NAG Fortran Compiler Release 5.3.1(907)
[NAG Fortran Compiler normal termination]
ian@ian-pc:~/test/stackoverflow$ ./read
10
 val =  10
10.0
 oh dear!!
safs
 oh dear!!
123dfs23
 oh dear!!
^C
ian@ian-pc:~/test/stackoverflow$ gfortran -o read read.f90
ian@ian-pc:~/test/stackoverflow$ ./read
10
 val =           10
10.0
 oh dear!!
dsfs
 oh dear!!
^C
ian@ian-pc:~/test/stackoverflow$ 

Upvotes: 1

Alexander Vogt
Alexander Vogt

Reputation: 18118

You can specify the format to request an integer:

program enter_int
  implicit none
  integer       :: ierror, intVal

  do
    write(*,*) "Enter an integer number"
    read(*,'(i10)',iostat=ierror) intval

    if ( ierror == 0 ) then
      exit
    endif
    write(*,*) 'An error occured - please try again'

  enddo

  write(*,*) 'I got: ', intVal
end program

Then, providing a float fails.

Upvotes: 4

Related Questions