Reading a sequence of integer in a line with unknown bound in fortran

前端 未结 2 1072
走了就别回头了
走了就别回头了 2021-01-22 20:41

I would like to read a sequence of integer in a line with unknown bound in FORTRAN. My question is similar to the following previous post,

Reading a file of lists of in

2条回答
  •  耶瑟儿~
    2021-01-22 21:06

    Something like this might satisfy your requirements

      INTEGER :: ix, rdstat
      INTEGER, DIMENSION(6) :: nums
      CHARACTER(len=128) :: aline
      ...
      OPEN(21,file='data.txt')
    
      DO ix = 1,10
         READ(21,'(a)',iostat=rdstat) aline
         IF (rdstat/=0) catch_errors()
    
         nums = -99 ! a guard
         READ(aline,*,iostat=rdstat) nums
         IF (rdstat/=0) catch_errors()
         ! do something with nums
      END DO
    
      CLOSE(21)
    

    I haven't thoroughly tested this and I haven't written catch_errors for you -- in practice you may not want to do very much. This first version is probably too brittle, but whether it's suitable or not depends heavily on the uniformity (or otherwise) of the input files.

    The strategy is to read each line into a character variable (one long enough for the entire line) and then to use internal, list-directed, reading to read 6 integers from the start of the character variable. This takes advantage of the in-built facility that list-directed input has of finding integers in an input stream with spaces separating values. The approach should work as well with a comma-separated list of integers. The internal read only looks for 6 integers, then catches the error when either no more integers are found, or only material which cannot be interpreted as integers (such as strings like # comment).

    Note

    • I've assumed a maximum line length of 128 characters, you may want to adjust that.
    • I've specified a fixed upper limit on the number of lines the program will read. You may want to change that, or change to a do/while loop.
    • The program expects no more than 6 integers in a line, as your question specifies.
    • At each line read the array nums is filled with -99 at each element; this is a 'guard'. If -99 is likely to occur in your input files you may want to change this.
    • It's entirely up to you what you do with the numbers in nums once you have them.

提交回复
热议问题