我试图读取四列数据文件。但是,因为我遇到了这么多麻烦,我只想尝试读取一列整数。这是我的代码:
program RFF_Simple
implicit none
! Variables
character(len = 100):: line_in
character(len = :), allocatable :: filename
integer, dimension(:), allocatable :: weight,numbers
real, dimension(:), allocatable :: fm, fc
integer :: iostat_1, iostat_2
integer :: lun, length, index
! Body of RFF_Simple
! filename = 'data.txt'
filename = 'data_test.txt'
iostat_1 = 0
iostat_2 = 0
length = 0
open(newunit = lun, file = filename, status = 'old', iostat = iostat_1)
!Count how many lines are in the file (length)
if (iostat_1 == 0) then
do while(iostat_2 == 0)
read(lun, '(a)', iostat = iostat_2) line_in
if (iostat_2 == 0) then
length= length + 1
endif
enddo
endif
rewind(lun)
allocate(numbers(length)) !Allocate arrays to have same length as number of lines
iostat_1 = 0 !Reset
iostat_2 = 0
index = 1 !This whole thing is confusing so I don't know whether starting from 1 or 0 is better....
if (iostat_1 == 0) then
do while(iostat_2 == 0)
if(iostat_2 == 0) then
read(lun,*, iostat = iostat_2) numbers(index) !This crashes the program (Severe 408)
index = index + 1
endif
enddo
endif
write(*,*) 'Press Enter to Exit'
read(*,*)
end program RFF_Simple
代码编译没有问题,但运行它会产生以下结果:http://imgur.com/a/6ciJS
是的我是一个打印屏幕。
我甚至不知道从哪里开始。
答案 0 :(得分:4)
这里的问题是你在每次成功阅读后增加index
。在上次成功阅读后,我们有index=length
。然后,您向index
添加1,然后尝试阅读numbers(length+1)
,这会导致违反边界。您可以使用常规的do循环,而不是使用do while
循环,因为我们知道要读取的行数。
do index = 1, length
read(lun,*) numbers(index)
enddo
您还可以测试index
是否大于length
并退出循环。