Fortran代码中已使用Go To命令时如何嵌套另一个Go To实现双层循环
你之前修改未达预期的核心原因有两个:
- 内层stations文件遍历完一次后,文件指针停在文件末尾,没有重置的话下次读取会直接触发结束条件,不会重新遍历内容
- 未正确调整跳转逻辑,原来的结束跳转直接终止程序,没有回到外层读取下一行event内容
按照要求用goto实现双层循环的修改后代码如下:
program events implicit none character*40 aline character*40 bline open (1, file="event", status="old") open (2, file="stations", status="old") open (3, file="output", status="new") ! 外层循环入口:每次读取一行event 20 read(1, '(a40)',end=60) aline ! 重置stations文件指针到开头,保证本次event行可以从头遍历所有站点 rewind(2) ! 内层循环:遍历当前event对应的所有stations行 1 read(2, '(a40)',end=20) bline write(3,*) aline, bline go to 1 60 stop end program events
修改说明:
- 新增外层循环标签
20作为event行的读取入口 - 每次读取到一行event内容后,通过
rewind(2)将stations文件的指针重置到文件头部 - 将内层stations读取的结束跳转目标从
60改为20:stations遍历完后回到外层读取下一行event,只有event文件全部读完触发结束条件时才会跳转到60终止程序
内容的提问来源于stack exchange,提问作者Sean Barnett Meyers
相关产品推荐
相关产品推荐

