我目前创建了一个代码,可以从放入目录中打开文件,然后开始将数据分类为两个不同的数组,一个整数和一个字符。输入文件如下所示:
1817
Plot50.0.xyz
C 0.70900 0.00000 0.00000
C 0.00000 1.22802 0.00000
C 2.12700 0.00000 0.00000
C 2.83600 1.22802 0.00000
C 4.96300 0.00000 0.00000
C 4.25400 1.22802 0.00000
C 6.38100 0.00000 0.00000
C 7.09000 1.22802 0.00000
C 9.21700 0.00000 0.00000
C 8.50800
数据文件
现在我不确定打开文件(格式等)时是否没有正确分配所有内容,但这是代码 [工作]:
program test01
character(len=40) :: filename !Storing the file name
character(len=20) :: nam !Collecting the file name within the file
integer(8) :: N !Number of coordinates within the file
real(8), allocatable :: coa(:,:) !Array containing xyz coordinates
character(len=6), allocatable :: atom(:,:) !Array containing the atomic make up
integer(8) :: i,j,k !Do loop parameters
filename = ''
write (6,*) 'Enter file name'
read (5,*) filename
open (10, file=filename, status='OLD')
write (6,*) 'Sucessfully opened file:', filename
read(10,*) N
allocate (coa(N,4))
allocate (atom(N,1))
read (10,*) nam
print*, nam
i = 0
do while (i < N)
read(10,*) atom(i,1), coa(i,2:4)
i = i+1
end do
print*, atom(0,1), atom(1,1), atom(4,1), atom(1818,1) !checking
print*, coa(0,2), coa(1500,3) !checking
close (10)
end program test01
所以我的主要问题在于,是否有更好的方法来创建数组(需要两个,因为我相信字符和真实不能混合,并且coa
数组在以后用于计算)并专门从文件中提取某些数据(更重要的是跳过文件的第 2 行,而不是将其插入字符以将其删除,因为它会导致所有问题当我尝试创建数组时)。
你写有没有更好的方法来创建数组。 让我们从一个正确的方法开始,这不是...
i = 0
do while (i < N)
read(10,*) atom(i,1), coa(i,2:4)
i = i+1
end do
这看起来像一个用Fortran编写的C循环(for (i=0; i<N; i++)
),它犯了在第0
行开始索引数组的错误。 由于代码不努力在0
启动数组索引,并且Fortran默认从1
索引,因此read
的第一次执行将数据读取到数组范围之外的内存位置。
一个正确和更Fortranic的方式是
do i = 1, N
read(10,*) atom(i,1), coa(i,2:4)
end do
我看到您在其他地方打印了数组第 0
行的值。 您很"幸运",这些越界访问不会转到程序地址空间之外的地址并导致分段错误。
它只是有点坏了,还没有给你带来任何痛苦。