如何读取未知宽度的变量? [英] How to read variables of unknown width?
问题描述
1 filedir / i03j12_fort.4
71 filedir / i04j01_fort.4
224 filedir / i04j02_fort.4
我使用以下命令获取初始整数,加上文件名中的'i'和'j'值(ldir是一个包含filedir长度的字符串)。
read(filenumber,'(i6,'// ldir //'x,i2,x,i2)')n,pix_i,pix_j
问题是整数之前的空白量在文件之间有所不同,所以我必须每次手动更改宽度。我也尝试过不指定一个格式,并读取整个文件名作为一个字符串,即
read(filenumber,*)n,filename
但文件名会返回奇怪的字符(尽管n有效)。
是否有任何格式语句会读取第一个wh的整数它发现它,以取代'我'以上?
谢谢!
!首先确定第一个整数
周围有多少空白!并将其存储为字符串ln
read(20,'(a)')filestring
write(ln,(I1))INDEX(filestring,'/') - 1
rewind (20)
!使用ln作为整数宽度
read(filenumber,'(i'// ln //','// ldir //'x,i2,x,i2)')n,pix_i,pix_j
I think this is quite a basic question, but I can't seem to find the answer. I'm trying to read a file of the following form:
1 filedir/i03j12_fort.4
71 filedir/i04j01_fort.4
224 filedir/i04j02_fort.4
I use the following command to get the initial integer, plus the 'i' and 'j' values from the filename (ldir is a string containing the length of filedir).
read(filenumber,'(i6,'//ldir//'x,i2,x,i2)') n,pix_i,pix_j
the problem is that the amount of whitespace preceding the integer varies between files, so I have to manually change the width each time. I have also tried not specifying a format, and reading the whole filename as a string, i.e.
read(filenumber,*) n, filename
but the filename returns weird characters (n works though).
Is there any format statement that will read the integer up to the first whitespace it finds, to replace the 'i6' I have above?
Thanks!
For completeness, here is my chosen solution, which relies on the fact that the string following the integer always starts with '/' (as it's a filepath):
! first determine how much whitespace is around the first integer
! and store this as string ln
read(20, '(a)') filestring
write(ln, "(I1)") INDEX(filestring, ' /')-1
rewind(20)
! use ln to as the integer width
read(filenumber,'(i'//ln//','//ldir//'x,i2,x,i2)') n,pix_i,pix_j
这篇关于如何读取未知宽度的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!