Fortran Simple I/O


Example

As an example of writing input & output, we'll take in a real value and return the value and its square until the user enters a negative number.

As specified below, the read command takes two arguments: the unit number and the format specifier. In the example below, we use * for the unit number (which indicates stdin) and * for the format (which indicates the default for reals, in this case). We also specify the format for the print statement. One can alternatively use write(*,"The value....") or simply ignore formatting and have it as

print *,"The entered value was ", x," and its square is ",x*x

which will likely result in some oddly spaced strings and values.

program SimpleIO
   implicit none
   integer, parameter :: wp = selected_real_kind(15,307)
   real(kind=wp) :: x
   
   ! we'll loop over until user enters a negative number
   print '("Enter a number >= 0 to see its square. Enter a number < 0 to exit.")'
   do
      ! this reads the input as a double-pricision value
      read(*,*) x
      if (x < 0d0) exit
      ! print the entered value and it's square
      print '("The entered value was ",f12.6,", its square is ",f12.6,".")',x,x*x
   end do
   print '("Thank you!")'
   
end program SimpleIO