Manuel Ramón
Manuel Ramón

Reputation: 2498

pass FORTRAN READ arguments into a string

I have a string including the names of the variables I want read, and I would like to pass this string to the read function. This could allow me to change the name of the variables I read just changing the vector with the names of the variables. An example could be:

PROGRAM test
implicit none

  integer :: no, age
  character(len=20) :: myname, vars

vars='no, myname, age'
read(*, '(i4,a20,i4)') vars
print*, no, myname, age 

END PROGRAM test

Is this possible?

Upvotes: 0

Views: 665

Answers (2)

Hristo Iliev
Hristo Iliev

Reputation: 74485

Fortran is a compiled language. It would be hard (to impossible) for the READ statement to extract variable addresses from the string list at run-time. That's why, as noted by janneb, Fortran provides the NAMELIST operator which became part of the language standard since Fortran 90 (some Fortran 77 also had support for namelists but it was non-standard and no compatibility was guaranteed between compilers). It is used like that:

...
NAMELIST /vars/ no, age, myname
...
READ(*, NML=vars)
...

The input should be something like this:

! Input can contain comments starting with exclamation marks

! And blank lines too
&vars
 no = 12,
 myname = 'sometext'/

Formatted input/output is not possible with NAMELIST though.

Upvotes: 1

janneb
janneb

Reputation: 37238

You can look into "NAMELIST" I/O, which maybe does what you're after. Often, namelist IO has various issues, and people often resort to writing their own custom IO routines anyway. But if it's enough for what you want, it's quite easy to use. E.g.


program nmltest
  implicit none
  real :: x
  integer :: y
  namelist /mynml/ x, y
  x = 4711
  y = 42
  write(*, mynml)
end program nmltest

Upvotes: 1

Related Questions