This shows you the differences between two versions of the page.
— | blog:fortran_var_arguments [2015/11/19 10:44] (current) – created - external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ==== Reading a variable number of elements in Fortran ==== | ||
+ | |||
+ | The code below locates the content in an input string. The in-arguments are the line to be read in, the maximum number of entries and a string with delimiters. After performing the routine, the out-arguments are the number of entries found, and two list of indices: startIxs(i) holds the starting point of entry i in line, and endIxs(i) holds the end point. | ||
+ | |||
+ | <code fortran> | ||
+ | !> Routine to help read a variable number of entries from a line. | ||
+ | ! In arguments: | ||
+ | ! line The line from which we want to read | ||
+ | ! delims | ||
+ | ! " | ||
+ | ! nEntriesMax | ||
+ | ! | ||
+ | ! Out arguments: | ||
+ | ! nEntries | ||
+ | ! startIxs | ||
+ | ! endIxs | ||
+ | subroutine splitLineByDelims(line, | ||
+ | | ||
+ | | ||
+ | | ||
+ | |||
+ | | ||
+ | |||
+ | | ||
+ | | ||
+ | |||
+ | do while (nEntries < nEntriesMax) | ||
+ | | ||
+ | ! Find the starting point of the next entry (a non-delimiter value) | ||
+ | ix = verify(line(prevIx+1: | ||
+ | if (ix == 0) exit ! No more entries | ||
+ | |||
+ | nEntries | ||
+ | startIxs(nEntries) | ||
+ | | ||
+ | ! Get the end point of the current entry (next delimiter index minus one) | ||
+ | ix = scan(line(startIxs(nEntries)+1: | ||
+ | | ||
+ | if (ix == -1) then ! If there is no last delimiter, | ||
+ | | ||
+ | else | ||
+ | | ||
+ | end if | ||
+ | | ||
+ | prevIx = endIxs(nEntries) | ||
+ | end do | ||
+ | |||
+ | end subroutine splitLineByDelims | ||
+ | </ | ||
+ | |||
+ | The above routine makes it quite easy to read in a variable amount of numbers. In many cases, this can just be done with the example code below (error checking has been left out for simplicity). | ||
+ | |||
+ | <code fortran> | ||
+ | do n = 1, nEntries | ||
+ | | ||
+ | end do | ||
+ | </ | ||