Warm tip: This article is reproduced from serverfault.com, please click

Escape sequence in a string literal (Fortran)

发布于 2020-10-23 05:21:35

There is an example in C++

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

The output will be

First
Second
Third;  

I wanna try to repeat it in Fortran and didn't find any info about escape-sequence in char string like in C++.

Questioner
Anton Golovenko
Viewed
0
amzon-ex 2020-10-23 13:58:18

One way would be to use achar with the ASCII code for linefeed, that is 10. The advantage of this method is, you can use other characters as necessary if you know the ASCII code.

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

Gives you the desired result. (Note: // is the character concatenation operator)

The other would be to replace achar(10) with new_line('a') and that works only for inserting linefeeds.

Interestingly, if you're using gfortran, you can use the option -fbackslash while compiling to use C-style backslashing, as mentioned in the documentation:

-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 \0 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.

Thus, the string would simplify to

str = "First\nSecond"