在Fortran 90程序中使用do循环读取n帧的不同行数? [英] Using do loop in a Fortran 90 program to read different number of lines for n frames?

查看:318
本文介绍了在Fortran 90程序中使用do循环读取n帧的不同行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个文件有1000帧。每一帧包含不同数量的行。每行有两列整数。但是,我不知道每一帧包含多少行。每一帧都由一条空行分隔。我想读取这些值并将它们存储在一个数组中。但是,我不能分配数组的大小,因为我不知道每帧有多少行。所以,我有两个问题:


  • 如何使用do循环读取fortran90程序中的不同行数?我不能使用count-controlled do循环,因为我不知道每帧中的确切行数。

  • 如果我无法分配大小,我该如何将数字存储在数组中它更早?
    该文件如下所示:





  1 2 
2 1

3 2

2 8
4 5
4 17
2 10

等等...



有什么建议吗?

解决方案

最简单的方法就是这样(如果需要的话,颠倒行和列索引的顺序并为所有变量添加声明I跳过以保持较短)。它首先读取文件并确定行数。然后将文件倒回从头开始并读取已知的行数。

  integer,allocatable :: a(: ,:) 
integer :: pair(2)
integer :: unit

unit = 11

open(unit,file =test。 txt)
n = 0
do
如果(io / = 0)退出
n = n + 1 $,读(单位,*,iostat = io)对
b $ b end do

倒带(单位)

分配(a(n,2))

do i = 1,n
read(unit,*)a(i,:)
end do

close(unit)

print *,a

end

一次性解决方案也可以完成,使用临时数组可以轻松地增长数组C ++向量在后台执行相同的操作)。你甚至可以实现你自己的增长能力的类,但它超出了这个问题的范围。


There is a file that has,say, 1000 frames. Each frame contains different number of lines.Each line has two columns of integers.But,I do not know how many number of lines each frame contains. Every frame is separated by one blank line.I want to read these values and store them in an array. But,I cannot allocate the array size as I do not know how many lines every frame has. So, I have two questions:

  • How can I use a "do" loop to read the different number of lines in a fortran90 program ? I cannot use "count-controlled do" loop as I do not know the exact number of lines in each frame.
  • How do I store the numbers in an array if I cannot allocate the size of it earlier ? The file looks something like this:

1   2  
2   1

3   2

2   8   
4   5  
4   17  
2   10

and so on...

Any suggestions?

解决方案

The easiest way is like this (reverse the order of indexes for row and column if necessary and add declarations for all variables I skipped to keep it short). It first reads the file and determines the number of lines. Then it rewinds the file to start from the beginning and reads the known number of lines.

  integer,allocatable :: a(:,:)
  integer :: pair(2)
  integer :: unit

  unit = 11

  open(unit,file="test.txt")
  n = 0
  do
    read(unit,*,iostat=io) pair
    if (io/=0) exit
    n = n + 1
  end do

  rewind(unit)

  allocate(a(n,2))

  do i=1,n
    read(unit,*) a(i,:)
  end do

  close(unit)

  print *, a

end

One pass solution also can be done, using temporary array you can grow the array easily (the C++ vector does the same behind the scenes). You could even implement your own grow able class, but it is out of scope of this question.

这篇关于在Fortran 90程序中使用do循环读取n帧的不同行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆