Fortran:将一行数字读入数组 [英] Fortran: reading a row of numbers into an array
问题描述
我有一行输入文件,其格式如下:
10110100000001011
我想用循环将每个数字读入一个数组元素。但是,如果我用
格式化它,请阅读(1,1i1)num(j),j = 1,10
它只读取第一个整数。我做错了什么?
格式 1I1
指示Fortran从记录/行读取一个整数,然后继续到下一个记录/行(我的意思是如果这就是格式所包含的全部)。如果您想要在一行上读取10个单位数字整数,请使用格式 10I1
。
< Fortran 2008添加了无限制格式项目,以便您在编写格式时不必知道项目数量:
*(i1)
。 这两种方法的代码示例:
程序tst
整数::数组1(10),数组2(10)
打开(单元= 20,文件=digits.txt,访问=顺序,窗体=格式化 )
read(20,'(10i1)')array1
write(*,*)array1
$ b rewind(20)
read(20 ,'(*(i1))')array2
write(*,*)array2
end program tst
I have an input file with one line formatted like so: 10110100000001011 And I would like to read each digit into an array element using a loop. But if I format it with Read (1, "1i1") num(j) , j =1,10 It only reads the first integer. What am I doing wrong?
The format 1I1
instructs Fortran to read a single integer from the record/line and then proceed to the next record/line (I mean if that's all that the format contains). If you want to read, e.g., 10 single-digit integers on a single line, then use the format 10I1
.
Fortran 2008 adds "unlimited format item" so that you don't have to know the number of items when you write the format: *(i1)
.
Code example of both methods:
program tst
integer :: array1 (10), array2 (10)
open (unit=20, file="digits.txt", access="sequential", form="formatted")
read (20, '(10i1)' ) array1
write (*, *) array1
rewind (20)
read (20, '( *(i1) )' ) array2
write (*, *) array2
end program tst
这篇关于Fortran:将一行数字读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!