Different CHARACTER lengths (3/4) in array constructor, how to trim strings - fortran

纵饮孤独 提交于 2019-12-09 00:34:34

问题


According to an answer to a similar question, I have declared the characters as indicated here gfortran does not allow character arrays with varying component lengths . However I would like to use a trim function because I need to add spaces to manually pad the names and these variables are then used in another part of the code. Can I trim at the same time as creating the array?

Error: Different CHARACTER lengths (3/4) in array constructor at (1)

If I add random characters to make them the same length it works but I can't do that for obvious reasons. I have compiled both with gfortran and mpif90 with same results

use mod_maxdims , only : maxstr
integer, parameter :: nvars_ncep = 12

character(len=maxstr), parameter, dimension(nvars_ncep) :: vars_ncep =                  &
                           (/ 'air'              & ! Air temperature                  [      K]
                            , 'pres'             & ! Pressure                         [     Pa]
                            , 'rhum'             & ! Relative humidity                [      %]
                            , 'uwnd'             & ! Zonal wind                       [    m/s]
                            , 'vwnd'             & ! Zonal wind                       [    m/s]
                            , 'pres'             & ! Pressure                         [     Pa]
                            , 'dlwrf'            & ! Downward long wave radiation     [   W/m2]
                            , 'nbdsf'            & ! Near-IR beam radiation           [   W/m2]
                            , 'nddsf'            & ! Near-IR diffuse radiation        [   W/m2]
                            , 'vbdsf'            & ! Visible beam radiation           [   W/m2]
                            , 'vddsf'            & ! Visible beam radiation           [   W/m2]
                            , 'prate'           /) ! Precipitation rate               [kg/m2/s]

回答1:


gfortran is preventing you from writing non-standard code; it's the language standard which forbids it, not the implementation.

If you initialise a character array as you have done then all the entries must have the same length. In your case you would have to pad each shorter entry with enough spaces to make them all equally long.

The alternative would be to insert the entries when program execution starts. If you write something like vars_ncep(1) = 'air' then the additional characters will be set to spaces, the compiler will take care of that for you. This however, would mean that your array could not be a parameter.



来源:https://stackoverflow.com/questions/29697314/different-character-lengths-3-4-in-array-constructor-how-to-trim-strings-fo

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