036. Reading user input#
topic: Input and Output
The read
statement is used to get data from the terminal or a file.
To handle errors, set the iostat
in the read
call and check afterwards if it is zero.
This program prompts the user for integers, one at a time, and prints their sum.
program sum_int
implicit none
integer :: i, ierr, isum
isum = 0
do
print *, "enter an integer, 0 to stop"
read (*, *, iostat=ierr) i
if (ierr /= 0) then
print *, "invalid input"
cycle ! return to beginning of loop
end if
if (i == 0) exit
isum = isum + i
end do
print *, "sum is", isum
end program sum_int
1
1
2
3
0
enter an integer, 0 to stop
enter an integer, 0 to stop
enter an integer, 0 to stop
enter an integer, 0 to stop
enter an integer, 0 to stop
sum is 7
Created with @carbon_app pic.twitter.com/pzKMXlNriJ
— FortranTip (@fortrantip) December 20, 2021
- 1
Compiled using
GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
with no flags