转义引号并删除fortran中的双换行符

时间:2018-11-04 21:16:47

标签: fortran fortran90

我正在尝试在Fortran90中输出一个简单的错误消息,如下所示:

error: failed to read '<file>'

但是我无法弄清楚如何产生单引号,将其转义会导致编译错误。我尝试了以下方法:

write(*, fmt="('error: failed to read: \'', a, '\'')") arg

另外,如果我在没有消息的情况下打印消息:

write(*, fmt="('error: failed to read: ', a)") file

在命令行上产生一个额外的换行符(即总共两个)。我通过执行arg获得了call getarg(1, arg),也许与它有关。

这是一个最小的工作示例,它演示了换行问题:

program foo                                                        
    character(len=100) :: arg

    call getarg(1, arg)

    write(*, fmt="('error: failed to read: ', a)") arg
end program foo

如果有人可以另外将我定向到可以更详细地说明这一点的资源,那我会发现fortran中的格式化输出非常不直观。

2 个答案:

答案 0 :(得分:4)

我认为最好不要像在C语言中那样将打印的字符串输入格式,而是将它们放入输出列表中。

我还建议在打印文件名trim(arg)时对其进行修剪,以免打印90个无用的尾随空白。

program foo
    implicit none                                                        
    character(len=100) :: arg

    call getarg(1, arg)

    write(*, '(*(a))') "error: failed to read: '", trim(arg), "'"
end program foo

这样,您就不需要一层引号来引用格式字符串本身。

即使在任何字符串中,您都可以重复引号以将其放入字符串中,即“''(请参见Difference between double and single quotation marks in fortran?

顺便说一句,标准的Fortran 2003具有子例程GET_COMMAND_ARGUMENT而不是GETARG

答案 1 :(得分:2)

如果您希望与原始示例保持一致,请总结以下三个修复程序。我还使用了可分配的字符变量,以获取信息[并且因为我喜欢该功能:-)]。您可以独立选择修复程序。

program foo
  ! always use implicit none at the beginning of a program
  implicit none
  ! use an allocatable character variable. The length can be specified later
  character(len=:), allocatable :: arg
  ! you need a variable to store the length of the argument
  integer :: arg_len

  ! obtain the length of the argument
  call get_command_argument(1, length=arg_len)
  ! allocate the character variable. the length is passed by the type definition of the
  ! allocate statement
  allocate(character(len=arg_len) :: arg)
  ! actually read the argument, finally!
  call get_command_argument(1, value=arg)

  ! the double quotes *inside* the string generate a single quote character
  ! the trim is not necessary here, as the character variable has the appropriate
  ! length. keep it if you stick to a fixed length character variable.
  write(*, fmt="('error: failed to read: ''', a, '''')") trim(arg)

end program foo
相关问题