问题
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