我正在尝试将文本文件读入关联数组。例如,“ text.txt”包含
1. ABC
2. XYZ
我想读取此文本文件并打印出来,例如Array[0]
为1. ABC
,Array[1]
为2. XYZ
我总共有6行输入!
这里是我现在所拥有的
program readText
OPEN(1,FILE='text.txt')
READ(1, *) A ,B, C, D, E, F
WRITE (*, *) A,B,C,D, E ,F
CLOSE(1)
end program readText
此后我得到
Error termination. Backtrace:
#0 0x10bde99ac
#1 0x10bdea645
#2 0x10bdeadd9
#3 0x10bfb3ecb
#4 0x10bfacab6
#5 0x10bfae509
#6 0x10bdddc82
#7 0x10bddde78
因此,我什至没有将文本文件打印到屏幕上。之后,我想将它们分配到一个数组中并打印该数组。请让我知道我可以做什么来解决这个问题。谢谢!
让我为您提供一个示例,其中将文本文件的内容写入动态字符数组。如果您使用的是FORTRAN,则强烈建议您使用显式变量声明。可以通过命令强制执行]
implicit none
否则,您必须关心FORTRAN的隐式变量定义,可以在here中找到它:
以I .. N开头的变量是
INTEGER
以其他字母开头的变量为REAL
将输入文件text.txt
扩展到6行:
1. ABC
2. XYZ
3. FOO
4. BAR
5. BYE
6. CKE
请使用该程序创建和填充字符数组,并将其打印到标准输出:
program readText
implicit none
integer :: FID = 1
character*256 :: CTMP
! 1. Assuming that no line of text.txt contains more than 256 characters
character*256, allocatable :: MY_ARRAY(:)
integer :: I = 0, IERR = 0, NUM_LINES = 0
open(unit=FID,file='text.txt')
! 2. Get number of lines
do while (IERR == 0)
NUM_LINES = NUM_LINES + 1
read(FID,*,iostat=IERR) CTMP
end do
NUM_LINES = NUM_LINES - 1
write(*,'(A,I0)') "Number of lines = ", NUM_LINES
! 3. Allocate array of strings
allocate(MY_ARRAY(NUM_LINES))
! 4. Read the file content
rewind(FID)
do I = 1, NUM_LINES
read(FID,'(A)') MY_ARRAY(I)
end do
! 5. Print array to standard output
do I = 1,size(MY_ARRAY,1)
write(*,*) trim(MY_ARRAY(I))
end do
deallocate(MY_ARRAY)
close(FID)
end program readText
输出看起来像这样:
Number of lines = 6
1. ABC
2. XYZ
3. FOO
4. BAR
5. BYE
6. CKE
希望有帮助。