Smart printing of integers in fortran90
Asked Answered
W

1

9

I'm learning Fortran90 after a brief introduction to Fortran77 a few years ago. When printing integers in Fortran, you must specify how many spaces you want to reserve for printing the integer. Consider this program...

implicit none

integer :: i
i = 123

write(*, '(A, I3, A)')  "'", i, "'"  !3 spaces for output = no padding
write(*, '(A, I5, A)')  "'", i, "'"  !5 is too many, so output is padded
write(*, '(A, I2, A)')  "'", i, "'"  !2 is too few, so output is jibberish
write(*, '(A, I:, A)')  "'", i, "'"  !Default behavior

end program

...which generates the following output.

'123'
'  123'
'**'
'         123'

How do I allocate the correct amount of space for integer printing when I do not know how many digits are in the integer?

Update: If your compiler is F95-compliant, you can use the I0 edit descriptor (i.e., put '(A, I0, A)' for the second argument of the write function in my example above. Thanks @janneb!

Walloping answered 21/1, 2011 at 15:35 Comment(0)
S
12

Use the I0 edit descriptor. Well, to be pedantic IIRC that is Fortran 95, so if you're really strict about no more than F90, then I suppose this won't work.

Salley answered 21/1, 2011 at 17:54 Comment(2)
If I understand the terminology correctly, the second argument of each of the 4 write statements in my example is the fmt argument, each of which contains 3 edit descriptors. Is my terminology correct? So yeah, the question isn't really about how to use descriptors, it's about what to put after the I. I can't use a static character string for the format because I don't know beforehand how long the strings will be. Do I understand your response correctly, or is an "IO edit descriptor" different from just any format edit descriptor?Walloping
Oops. I didn't understand your response at first, now I see you're talking about a specific edit descriptor. I used I0 as the edit descriptor and it worked! I guess the compilers on the machine I'm using are indeed F95 compliant. Thanks!Walloping

© 2022 - 2024 — McMap. All rights reserved.