字符串文字中的转义序列 (Fortran)

Escape sequence in a string literal (Fortran)

C++中有一个例子

string str;
str = "First\n"
      "Second\n"
      "Third;\n";
cout << str << endl;

输出将是

First
Second
Third;  

我想尝试在 Fortran 中重复它,但没有像在 C++ 中那样在 char 字符串中找到任何关于转义序列的信息。

一种方法是使用 new_line() 内在和 // 连接运算符:

program main
  implicit none
  character(128) :: str
  character      :: NL = new_line("a")

  str = "first"//NL//"second"//NL//"third"
  write (*,"(a)") str

end program main

一种方法是使用 achar 换行 的 ASCII 码,即 10。这种方法的好处是,如果你知道ASCII码,你可以根据需要使用其他字符。

character(len=32):: str = "First" // achar(10) // "Second"

给你想要的结果。 (注://为字符连接运算符)

另一种方法是将 achar(10) 替换为 new_line('a'),这仅适用于插入换行符。

有趣的是,如果您使用 gfortran,您可以在编译时使用选项 -fbackslash 以使用 C-style 反斜杠,如文档中所述:

-fbackslash

Change the interpretation of backslashes in string literals from a single backslash character to “C-style” escape characters. The following combinations are expanded \a, \b, \f, \n, \r, \t, \v, \, and [=19=] to the ASCII characters alert, backspace, form feed, newline, carriage return, horizontal tab, vertical tab, backslash, and NUL, respectively. Additionally, \xnn, \unnnn and \Unnnnnnnn (where each n is a hexadecimal digit) are translated into the Unicode characters corresponding to the specified code points. All other combinations of a character preceded by \ are unexpanded.

因此,字符串将简化为

str = "First\nSecond"