简体   繁体   中英

Reading variable length real values in fortran

I have a file with the following text:

-1.065211      246.0638 xlo xhi
-0.615       245.385 ylo yhi
-10 10 zlo zhi

I want to read the numerical values on the lines into a 3*2 real matrix.
Is it possible to read only two inputs of a record and go to the next line? Something like:
read(1,'(2F?.?/)') (matrix(i,1:2),i=1,3)
I've put question marks in F?.? because the length of my numbers are variable. In other words, I need to read only two items of the record in free-format. I understand that you can do this by a loop. I'm wondering if an elegent one-liner is possible.

You can achieve what you want with

do i = 1, 3
   read(fd,*) matrix(i,:)
end do

where it is assumed that fd is connected to the file containing your data.

The code in @Steve's answer is the simplest one that can accomplish what you want. If you want it in one line , you can simply

do i=1,3 ; read(fd,*) matrix(i,:) ; end do

If what you are looking for is a way to "read only two inputs of a record and go to the next line" with only one statement , that is, to my knowledge, not possible: Since your real values have different formats, you need to use list-directed input (an asterisk in the format) in order to read multiple lines with the same statement (all other formats for reals require a positive width for input, and since your reals have different widths any specification of a width would result in a runtime error).

If you want to only use one statement, you will need to explicitly tell the program to read the two strings at the end of each line, even if they are discarded (otherwise the program will try to run a string into a real number, and this will result in a runtime error):

character(len=10) :: r
read(1,*) (a(i,:),r,r,i=1,3)

This is less general than @Steve's code (requires that you have exactly 2 character strings per line), and actually requires the additional declaration of the character variable.

Finally, note that you are not reading the array in element sequence order: in Fortran, the order of the elements of the array in the memory is a(1,1) , a(2,1) , a(3,1) , a(1,2) , etc. If the actual arrays you are planning on manipulating are much bigger, the order of the indices may dramatically affect performance, since your consecutive memory accesses may address distant parts of the memory rather than contiguous parts of it. When you are writing a program in Fortran, as in any other language (which may use a different ordering), you need to give some thought to the order of the indices of arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM