reading input file in fortran

放肆的年华 提交于 2019-12-12 05:38:58

问题


I am looking for reading a file, like:

NE                32         0
IBZINT             2
NKTAB            936
XC-POT    VWN       
ITER          29
MIX     2.00000000000000E-01
TOL     1.00000000000000E-05

I was thinking it is index intrinsic that I am looking for, and was writing a code accordingly:

EDIT The code is updated,

   Implicit None
    integer ::i,pos
    character(50) :: name
    character(len=16),dimension(100)::key,val
    key(1)="NE"
    open(12,file="FeRh/FeRh.pot_new",status="old")
    do i=1,100
      read(12,*)name
      if (name(1:2)==key(1))then
        write(*,*)"find NE"
        write(*,*)name(1:2)
        write(*,*)name(index("NE","")+21)
      endif
    end do
    close(12)
    !write(*,*)index(key(1),"")
    End Program  readpot

I am expecting to have 32 in the 3rd write statement. Must have gone horribly wrong some where. can you kindly help?


回答1:


When you want to read a line from the file you are using list-directed (* as the format) input. This isn't what you want as there will be some limited parsing by the run-time.

That is, read(12,*) name on the first record will result in "NE" padded with lots of spaces in the variable name as the record will be split on the spaces.

As you want the entire line in name, use the format '(A)' in the read.

Once you have that line, you can then do your further parsing. However, from what you show index doesn't seem to be helping, especially as you are checking against an empty substring. You know the length of the key (using len_trim) so if you have a match you know the location of the first separator.




回答2:


If I wanted to read a line such as

NE                32         0

I'd write a statement such as

read(12,*) name, int1, int2

and expect my processor to set name to NE, int1 to 32 and int2 to 0, if, that is, I'd declared int1 and int2 to be integers.

I'm puzzled that you seem to want to read a line of text and then parse it, all the while ignoring the benefits of list-directed input. If you do want to parse it into something other than a character variable and two integers, let us know.



来源:https://stackoverflow.com/questions/21409601/reading-input-file-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!