How to use a variable in the format specifier statement?

五迷三道 提交于 2019-12-11 05:06:38

问题


I can use:

write (*, FMT = "(/, X, 17('-'), /, 2X, A, /, X, 17('-'))") "My Program Name"

to display the following lines on the console window:

-----------------
 My Program Name
-----------------

Now, I want to show a pre-defined character instead of - in the above format. I tried this code with no success:

character, parameter :: Chr = Achar(6)

write (*, FMT = "(/, X, 17(<Chr>), /, 2X, A, /, X, 17(<Chr>))") "My Program Name"

Obviously, there are another ways to display what I am trying to show by means of a variable in the format specifier statement. For instance:

character, parameter :: Chr = Achar(6)
integer :: i, iMax = 17

write (*, FMT = "(/, X, <iMax>A1, /, 2X, A, /, X, <iMax>A1)") (Chr, i = 1, iMax), &
                                                              "My Program Name",  &
                                                              (Chr, i = 1, iMax)

However, I would like to know if there is any way to use a variable or invoke a function in the format specifier statement.


回答1:


The code you are trying to use (<>) is not standard Fortran. It is an extension accepted by some compilers. Just build the format string as a string.

"(/, X, 17(" // Chr // "), /, 2X, A, /, X, 17(" // Chr // "))"

For the the numeric case you have to prepare a string with the value

write(chMax, *) iMax

"(/, X, " // chMax // "A1, /, 2X, A, /, X, " // chMax // "A1)"

or you can use some function, if you have it

"(/, X, " // itoa(iMax) // "A1, /, 2X, A, /, X, " // itoa(iMax) // "A1)"

but it may still be preferable to call it beforehand, to avoid multiple calls.

The function can look like:

function itoa(i) result(res)
  character(:),allocatable :: res
  integer,intent(in) :: i
  character(range(i)+2) :: tmp
  write(tmp,'(i0)') i
  res = trim(tmp)
end function


来源:https://stackoverflow.com/questions/27189975/how-to-use-a-variable-in-the-format-specifier-statement

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