How to read the second column of a text file in fortran and then allocate it in an array?

171 Views Asked by At

I have a text file with two colums with real numbers.

How can I import the numbers from the second colum in an array ?

I think I first need to define an allocatble array, then read my text file and then allocate the second column to the array, but I don't know how to properly do it.

The text file looks like this:

1850     0.23

1851     0.56

1852     0.73

...

2000     0.98

(Two colums but I only need the second one (not the years))

My try:

program FINAL_PROJECT_A2 


      implicit none

real F_in_obs(0:150), funky

open(unit=10,file='Fin_obs.txt',status='old')

                  read(10,*) funky

                           do i=1,150

                                F_in_obs(i)=funky(2,i)

                           enddo

                  close(unit=10)

The error message is the following:

 F_in_obs(i)=funky(2,i)                  
                                1

Error: Unclassifiable statement at (1)

1

There are 1 best solutions below

3
On

I think that the following code with what you're looking for if you don't know how many lines the file has at the start. Assuming that you're dealing with Modern Fortran, which allows you to use allocatable arrays, then you don't need to know how long the file is at the beginning. You can figure out how many lines are in your file by running through it once.


    integer :: nlines = 0, io, i
    real, allocatable, dimension(:) :: array
    real :: skip
    open(1,file = 'test.txt')
    do
        read(1,*,iostat=io)
        if(io /= 0) exit
        nlines = nlines + 1
    end do

Then be sure to rewind your file with rewind(1) to start back at the end of the file. Then you can allocate the size of your data array like, allocate(array(nlines)). Then just loop through the array. In my example below, I just have the first column of data being written to a junk variable.

    do i = 1,nlines
        read(1,*) skip, array(i)
    end do