Skip to content
Format Strings
step 1/5

Reading — step 1 of 5

Learn

~2 min readSubroutines, Functions, Format I/O

Fortran's print and write use format strings — terse but very precise output control. Inherited from FORTRAN 66 and barely changed.

Edit descriptors

  • I — integer (I5 = 5-char field, I0 = exact width)
  • F — float (F8.2 = 8 chars, 2 after decimal)
  • E — scientific notation (E12.4 = 12 chars total)
  • A — character/string (A20 = 20-char field, padded right)
  • L — logical
  • X — space (5X = 5 spaces)
  • T — tab to column (T20 = column 20)
  • / — newline

Examples

integer :: i = 42
real :: r = 3.14159
character(len=10) :: name = "Ada"

write(*, '(I0)') i               ! 42
write(*, '(I5)') i               !    42 (right-padded to 5)
write(*, '(F8.2)') r             !     3.14
write(*, '(F0.2)') r             ! 3.14 (no leading spaces)
write(*, '(A)') name             ! "Ada       " (10 chars)
write(*, '(A,I0)') "Age: ", i    ! "Age: 42"

write(*, '(I0,1X,F0.2)') i, r    ! 42 3.14

write(*, '(I0)', advance='no') i   ! no newline
write(*, '(/, A)') "after blank line"

Format reuse with format statements

100 format(I0, 1X, F8.3)        ! labeled format
write(*, 100) age, height

list-directed (free format)

* as the format = compiler picks a default:

print *, i, r, name              ! "          42   3.1415900     Ada"

Readable in interactive code, ugly for production output.

Repeating descriptors

write(*, '(5I4)') 1, 2, 3, 4, 5   ! "   1   2   3   4   5"
write(*, '(3(A,I0,1X))') "a=", 1, "b=", 2, "c=", 3

Reading with format

read(*, '(I5)') i               ! read exactly 5 cols as int
read(*, '(F8.2)') r              ! read 8 chars, 2 decimals implied

For flexibility, list-directed read (read *, i) is what most code uses.

printing without leading space

print *, x and write(*,*) add a leading space (historical: column 1 was reserved for "carriage control").

write(*, '(A)') "text" — no leading space.

For exact output, prefer the explicit format.

Lookup table

ValueFormatOutput
42I042
42I5 42
42.0F0.242.00
42.0F8.2 42.00
42.0E10.3 0.420E+02
"hi"Ahi
"hi"A5 hi

Fortran format is famously esoteric — but once you know the basic descriptors, it's quite powerful.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…