如何打印带有引号的 Fortran 字符串?

wan*_*r95 2 fortran

假设我有一个如下的 Fortran 程序:

      character*30 changed_string1
      changed_string1="hello"
      write(*,"(A)")changed_string1(1:3)
      end
Run Code Online (Sandbox Code Playgroud)

我想用引号打印字符串,以便我可以准确地看到前导和尾随空格。这该怎么做?

fra*_*lus 7

没有用于将它们与分隔符一起输出的字符的编辑描述符。字符变量没有像出现在文字字符常量中的那些“自动”定界符(尽管可能将它们作为内容)。

这意味着您必须自己明确打印任何选定的分隔符,将它们添加到格式中或按照Vladimir F's answer 进行连接

同样,您也可以将分隔符添加到输出列表中(相应的格式更改):

write (*,'(3A)') '"', string, '"'
Run Code Online (Sandbox Code Playgroud)

您甚至可以编写一个返回“分隔字符串”的函数,并在输出列表中使用结果:

  implicit none

  character(50) :: string="hello"
  print '(A)', delimit(string,'"')

contains

  pure function delimit(str, delim) result(delimited)
    character(*), intent(in) :: str, delim
    character(len(str)+2*len(delim)) delimited

    delimited = delim//str//delim
  end function delimit

end program
Run Code Online (Sandbox Code Playgroud)

上面的函数结果甚至可以是延迟长度(character(:), allocatable :: delimited)以避免显式声明结果长度。


正如 yamajun 在评论中提醒我们的那样,格式化输出的连接有一个分隔符模式,它允许将引号和撇号自动添加到列表导向和名称列表输出的输出中(仅限)。例如,我们可以控制特定数据传输语句的分隔符模式:

write(*, *, delim='quote') string
write(*, *, delim='apostrophe') string
Run Code Online (Sandbox Code Playgroud)

或者对于整个连接:

open(unit=output_unit, delim='quote')  ! output_unit from module iso_fortan_env
Run Code Online (Sandbox Code Playgroud)

不要忘记列表导向的输出会将前导空白添加到您的输出中,如果您的字符输出项中有引号或撇号,您将不会看到完全相同的表示(这甚至可能是您想要的):

use, intrinsic :: iso_fortran_env, only : output_unit
open(output_unit, delim='apostrophe')

print*, "Don't be surprised by this output"

end
Run Code Online (Sandbox Code Playgroud)

Fortran 2018 不允许以这种方式任意选择分隔符,但这仍然适用于某些用途。