Formatted IO
| List-directed print | |
| Format specs | |
| Widths that fit | |
| Star format |
List-directed print
List-directed output is the fastest way to see values: print followed by a star and a list prints each item with readable spacing.
You give up layout control, but for debugging and small tools the default spacing is exactly what you want.
program listed
implicit none
integer :: n
real :: price
n = 42
price = 2.5
print *, n, price
end program listed
./listed
42 2.5000000
Format specs
A format string spells out the layout: A prints text, I5 reserves five slots for an integer, and F6.2 prints a real with two decimals.
Each item in the write list matches one spec in order, so the label, the count, and the price land exactly side by side.
program specs
implicit none
integer :: n
real :: price
n = 42
price = 2.5
write(*, "(A, I5, F6.2)") "n=", n, price
end program specs
./specs
n= 42 2.50
Widths that fit
Widths must fit the value: I5 gives room to spare, I2 fits 42 exactly, and I1 is too narrow so Fortran prints stars instead.
Stars are a loud hint to widen the field, which beats silent truncation of your numbers every time.
program widths
implicit none
write(*, "(I5)") 42
write(*, "(I2)") 42
write(*, "(I1)") 42
end program widths
./widths
42
42
*
Star format
The star format means list-directed inside a write statement: write with a star behaves like print and picks spacing for you.
Use it for logs and drafts, then switch to explicit specs when the layout must look polished.
program star
implicit none
integer :: a
integer :: b
a = 7
b = 9
write(*, *) a + b
print *, a + b
end program star
./star
16
16
Next: Files
Article author: Arthur Isaev