String Formatting in Co-array Fortran
program string_formatting
use iso_fortran_env
implicit none
type :: point
integer :: x, y
end type point
type(point) :: p
character(len=30) :: s
! Initialize the point
p = point(1, 2)
! Print the struct
print '(A,I0,A,I0,A)', 'struct1: {', p%x, ' ', p%y, '}'
! Print the struct with field names
print '(A,I0,A,I0,A)', 'struct2: {x:', p%x, ' y:', p%y, '}'
! Print the type
print '(A)', 'type: point'
! Print boolean
print '(A,L1)', 'bool: ', .true.
! Print integer
print '(A,I0)', 'int: ', 123
! Print binary representation
print '(A,B0)', 'bin: ', 14
! Print character
print '(A,A1)', 'char: ', achar(33)
! Print hexadecimal
print '(A,Z0)', 'hex: ', 456
! Print float
print '(A,F0.6)', 'float1: ', 78.9
! Print scientific notation
print '(A,ES12.6)', 'float2: ', 123400000.0
print '(A,ES12.6)', 'float3: ', 123400000.0
! Print string
print '(A,A)', 'str1: ', '"string"'
! Print quoted string
print '(A,A)', 'str2: ', '"""string"""'
! Print hexadecimal representation of string
print '(A,Z2.2,Z2.2,Z2.2,Z2.2)', 'str3: ', iachar('h'), iachar('e'), iachar('x'), iachar(' ')
! Print pointer (address not directly accessible in Fortran)
print '(A)', 'pointer: Not directly accessible in Fortran'
! Print with width
print '(A,I6,I6)', 'width1: |', 12, 345
! Print float with width and precision
print '(A,F6.2,F6.2)', 'width2: |', 1.2, 3.45
! Left-justified float
print '(A,F6.2,F6.2)', 'width3: |', 1.2, 3.45
! Print string with width
print '(A,A6,A6)', 'width4: |', 'foo', 'b'
! Left-justified string
print '(A,A6,A6)', 'width5: |', 'foo', 'b'
! Equivalent to Sprintf
write(s, '(A,A)') 'sprintf: a ', 'string'
print '(A)', trim(s)
! Equivalent to Fprintf
write(error_unit, '(A,A)') 'io: an ', 'error'
end program string_formatting
This Co-array Fortran program demonstrates various string formatting techniques. Here are some key points:
Fortran uses format specifiers for printing, which are similar to the format verbs in other languages.
The
print
statement is used for standard output, whilewrite
can be used for other units (like error_unit for standard error).Fortran doesn’t have a built-in struct type, so we define a custom type
point
.Some concepts like pointers and hexadecimal representation of strings are not directly available in Fortran, so alternatives or explanations are provided.
Fortran uses different format specifiers for different data types. For example, ‘I’ for integers, ‘F’ for floats, ‘ES’ for scientific notation, etc.
String manipulation in Fortran is somewhat different from other languages. Strings are fixed-length by default, and we use the
trim
function to remove trailing spaces.Fortran doesn’t have a direct equivalent to
sprintf
, but we can use internal writes to achieve similar functionality.Error output is directed to the predefined
error_unit
.
This program covers most of the formatting examples from the original, adapted to Fortran’s syntax and capabilities.