Read a file with an unknown number rows in Fortran

前端 未结 1 1669
时光取名叫无心
时光取名叫无心 2021-01-03 18:58

Heroes the new code I used. I have tried this, and it works if I have n declared first, which is not what I want. I need to know the total number of rows (n) and use that n

相关标签:
1条回答
  • 2021-01-03 19:43

    You can't declare variables with unknown dimension "dimension(1:n)".

    This program first reads the file to determine the number of rows:

    program reading
      implicit none
    !  variable declaration 
      real, dimension(:) ,allocatable :: x ,y 
      real :: dist
      integer:: i, j ,n ,io
    
      open(2, file = 'xyBVNData_R.txt', status = 'old', action = 'read')
    
      n = 0 
      DO
        READ(2,*,iostat=io)
        IF (io/=0) EXIT
        n = n + 1
      END DO
      print*, n
    
      allocate( x(n) ,y(n) )
      rewind(2)
      DO i =1,n
        READ(2,*) x(i),y(i)
      END DO
    
      dist=0.0
      DO i=1,n
        DO j=1,n
          dist = dist + sqrt( (x(i)-x(j))**2 + (y(i)-y(j))**2 )
        END DO
      END DO
    
      ! writing and saving 
      DO i= 1, n 
        write(*,*) i, x(i)
      END DO
    
    end program reading
    

    Another alternative (Fortran 2003), it reallocates the arrays x and y by adding the new element when a new line is read:

    program reading
      implicit none
    !  variable declaration 
      real, dimension(:) ,allocatable :: x ,y 
      real :: dist ,x_tmp ,y_tmp
      integer:: i, j ,n ,io
    
      open(2, file = 'xyBVNData_R.txt', status = 'old', action = 'read')
    
      n = 0 
      allocate( x(0) ,y(0) )
      DO
        READ(2,*,iostat=io) x_tmp,y_tmp
        x = [x,x_tmp]
        y = [y,y_tmp]
        IF (io/=0) EXIT
        n = n + 1
      END DO
      print*, n
    
      dist=0.0
      DO i=1,n
        DO j=1,n
          dist = dist + sqrt( (x(i)-x(j))**2 + (y(i)-y(j))**2 )
        END DO
      END DO
    
      ! writing and saving 
      DO i= 1, n 
        write(*,*) i, x(i)
      END DO
    
    end program reading
    
    0 讨论(0)
提交回复
热议问题