2

I have a text file formatted like this:

1  2 
3  4  5
6  7    

and so on for many lines.

I run this fortran program:

i=1
tt=1
do while(.true.)
  read(unit=1,*,IOSTAT=status) lon(i,tt),lat(i,tt),h(i,tt)
  i=i+1
  if(status/=0)exit
enddo

I want to assign three numbers in the same line to lon, lat, h. However, because the first line doesn't have the third element , the program will read the first element in the second line (i.e., 3 to h(i,tt)), and that's not what I want. I want to set h(i,tt) to the missing value in some lines

How can I do this?

Dan
  • 12,157
  • 12
  • 50
  • 84
music_piano
  • 638
  • 7
  • 9
  • could you read a line at a time and the parse each value into the appropriate structure – web_bod May 19 '12 at 02:51
  • Maybe you can look at the answers to [this](http://stackoverflow.com/questions/10095342/reading-a-known-number-of-variable-from-a-file-when-one-of-the-variables-are-mis) question. – alexurba May 19 '12 at 19:27
  • 2
    These similar questions may help: http://stackoverflow.com/questions/10259712/reading-comment-lines-correctly-in-an-input-file-using-fortran-90 and http://stackoverflow.com/questions/7314216/reading-data-file-in-fortran-with-known-number-of-lines-but-unknown-number-of-en/7315185 – M. S. B. May 19 '12 at 21:29

1 Answers1

1

For your specific example, you can try something like this:

program test

  integer :: status, i, tt
  character(len=100) :: line
  integer :: lon(3, 1), lat(3, 1), h(3, 1)

  lon(:, :) = 0
  lat(:, :) = 0
  h(:, :) = 0

  open(unit=1, file='data.txt')
  i=1
  tt=1
  do

     read(1, '(A100)', iostat=status) line
     if(status/=0) exit

     read(line, *, iostat=status) lon(i, tt), lat(i, tt), h(i, tt)

     if(status/=0) then
        read(line, *) lon(i, tt), lat(i, tt)
        h(i, tt) = 1  ! default value
     end if

     i = i + 1

  end do

  print *, 'lon=', lon
  print *, 'lat=', lat
  print *, 'h=', h

end program test

which returns

lon=           1           3           6
lat=           2           4           7
h=           1           5           1
astrofrog
  • 32,883
  • 32
  • 90
  • 131