Trying to read a 2 column input file into two separate arrays and having a lot of trouble

arrays, fortran

Solution

`read (...) t, tuvr` reads the entire arrays at once, in a block. You want to read them one element at a time since that is how they are file. Like this:

do i=1, 1440
   read (1, '(i5,f8.3)' ) t(i), tuvr(i)
end do

Depending on whether or not the numbers in the file are perfectly in columns, you might find it necessary to use list-directed IO: `read (1, *) t(i), tuvr(i)`. This method is very flexible and easy to use.

If the file might have less than 1440 lines, try something like this, which detects the end of file and counts how many lines were read:

program test

use, intrinsic :: iso_fortran_env

implicit none

integer, parameter :: ArrayLen = 1440
INTEGER, DIMENSION(ArrayLen) :: t
REAL, DIMENSION(ArrayLen) :: tuvr
integer :: i, ReadCode, num


num = 0
ReadLoop: do i=1, ArrayLen

   read (1, '(i5,f8.3)', iostat=ReadCode ) t(i), tuvr(i)

   if ( ReadCode /= 0 ) then
      if ( ReadCode == iostat_end ) then
         exit ReadLoop
      else
         write ( *, '( / "Error on read: ", I0 )' )  ReadCode
         stop
      end if
   end if

   num = num + 1

end do ReadLoop

end program test

Problem

This is likely a trivial question, but for some reason I'm having a lot of trouble solving this problem. I'm reading from an input file which has to sets of numbers in two columns. The first column is a list of integers representing time(e.g. 0530). The second column is a list of real data 5 digits long with 3 digits after the decimal place(e.g. 19.213). The two columns have 3 spaces in between. I would like to read this into my program into separate arrays. I've stat the dimensions of the arrays at the maximum possible length(1440), as is shown below. Id like to use this arrays in a function eventually, but i cant even get the input to work properly. Thanks for the help. ``` PROGRAM readtest1 IMPLICIT NONE INTEGER, DIMENSION(1440) :: t REAL, DIMENSION(1440) :: tuvr OPEN(1, FILE='AP2412.tv', STATUS='old', ACTION='read') OPEN(2, FILE='timetuvr.txt', STATUS='replace', ACTION='write') READ(1,100) t, tuvr 100 FORMAT(I5, F8.3) WRITE(2,100) t, tuvr END PROGRAM readtest1 ``` Oh and when I compile and run the program i get the error 'FORTRAN runtime error: Expected REAL for item 2 in formatted transfer, got INTEGER) I believe that fortran is reading directly down the column, which is causing this problem, but I'm unsure of how to fix it. Do i need a double loop?

Original source