Fortran主程序调用to_upper函数如何正确声明以解决编译报错
问题解决办法
报错根因
Fortran语法规定,character(*) 即假定长度字符类型仅允许在以下三个场景使用:
- 子程序/自定义函数的虚拟输入参数
- 被
PARAMETER修饰的字符常量 - 显式接口声明下的函数返回值
你主程序里给普通局部变量tes1、tes2,以及外部函数to_upper加character(*)声明都违反了上述规则,因此抛出编译错误。
正确修改方案
方案1:最简修改(无需调整函数结构)
直接给主程序的变量、函数返回值指定固定长度即可,修改后的主程序代码如下:
program tescc implicit none ! 指定函数返回值长度为足够覆盖所有输入场景的固定值,比如20 character(len=20) :: to_upper ! 普通字符变量指定固定长度 character(len=20) :: tes1, tes2 tes1 = 'LoWs' tes2 = to_upper(tes1) ! 用trim去掉尾部多余空格输出 print*, trim(tes1), ',', trim(tes2) end
方案2:规范写法(推荐)
将自定义字符串函数封装到模块中,主程序通过use引用模块即可自动获取函数显式接口,无需手动声明函数返回值长度,还能支持动态匹配输入字符串长度返回对应长度的结果:
完整可运行代码:
! 字符串工具模块 module str_utils implicit none contains Pure Function to_upper (str) Result (string) ! 将输入字符串转为大写 Implicit None Character(*), Intent(In) :: str Character(LEN(str)) :: string Integer :: ic, i do i = 1, len(str) ic = iachar(str(i:i)) ! 小写字母转大写,其余字符保留 if (ic >= iachar('a') .and. ic <= iachar('z')) then string(i:i) = achar(ic - 32) else string(i:i) = str(i:i) end if end do End Function to_upper end module str_utils ! 主程序 program tescc use str_utils implicit none ! 也可使用Fortran2003支持的自动分配长度字符变量:character(len=:), allocatable :: tes1, tes2 character(len=20) :: tes1, tes2 tes1 = 'LoWs' tes2 = to_upper(tes1) print*, trim(tes1), ',', trim(tes2) end program tescc
内容的提问来源于stack exchange,提问作者Steven Lord
相关产品推荐
相关产品推荐

