Interpret strings as variable names in Fortran [duplicate]

淺唱寂寞╮ 提交于 2021-01-27 21:03:54

问题


I'd like to access a real variable with a name equal to a string of characters that I have. Something like this (I'll make the example as clean as possible):

character(len=5) :: some_string
real :: value
value = 100.0
some_string = 'value'

At this point, how do I create an association between the character array value and the name of my real variable, value, so that I can write the value of 100.0 by referring to the string some_string?


回答1:


That's pretty much not going to happen in Fortran. There are no "dynamic" language features like this available in the language. Variable names are a compile-time only thing, and simply don't exist at runtime (the names have been translated to machine addresses by the compiler).




回答2:


This is how I work around this:

character(100) :: s
integer        :: val  
val = 100   
write(s,*) val   
print *,trim(s)

This prints 100 to the screen. There is some strangeness which I do not understand however, the character s needs to be very large (100 int his case). For instance, if you use 3 instead of 100, it does not work. This is not a critical thing, as the use of trim fixes this, but it would be nice if somebody could answer why this is the case.

Either way, this should work.



来源:https://stackoverflow.com/questions/9268418/interpret-strings-as-variable-names-in-fortran

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