Allocatable character variables in Fortran

北城以北 提交于 2019-11-30 23:10:46

问题


My code (stripped down to what I think is relevant for this question) is

PROGRAM test

IMPLICIT NONE

CHARACTER(len=37) input
CHARACTER(len=:), allocatable :: input_trim


WRITE(*,*) 'Filename?'
READ(*,*) input
ALLOCATE(character(len=LEN(TRIM(input))) :: input_trim)
input_trim=trim(input)

.
.
.

END PROGRAM test

It works fine with Intel's Fortran compiler, however gfortran gives me a couple of errors, the first one being in the line saying

CHARACTER(len=:), allocatable :: input_trim

I'm not sure which compiler is 'right' regarding the Fortran standard. Plus I don't know how to achieve what I need in a different way?! I think what I'm doing is more of a workaround anyway. What I need is a character variable containing exactly the filename that was entered with no following spaces.

EDIT: The error is "Syntax error in CHARACTER declaration". gfortran --version gives me "GNU Fortran (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)"

EDIT 2: You're right regarding the allocate: With ifort, I don't need it. And gfortran crashes before that so maybe it doesn't need the allocate either but I cannot test this at the moment...


回答1:


This

character (len=:), allocatable :: input_trim

is certainly syntactically correct in Fortran 2003. You don't say what the error that gfortran raises is, so I can't comment on why it doesn't accept the line -- perhaps you have an old version of the compiler installed.

With an up-to-date Fortran compiler (eg Intel Fortran v14.xxx) you don't need to allocate the character variable's size prior to assigning to it, you can simply write

input_trim = trim(input)

Note that

read(*,*) input_trim

won't work.



来源:https://stackoverflow.com/questions/20908053/allocatable-character-variables-in-fortran

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