Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28996 Discussions

formatted write, allocatable character array

Alexis_R_
New Contributor I
570 Views
This program:
[fortran]program test
implicit none

character(len=:), allocatable, dimension(:) :: list
character(len=*), parameter :: header_10 = ' 1 2 3 4 5'
character(len=*), parameter :: header_1 = '12345678901234567890123456789012345678901234567890'
!

list = ['pear', '5', 'apple', 'foo', 'J']

write(*,'(A)') header_10
write(*,'(A)') header_1
write(*,'(5(A10))') 'pear', '5', 'apple', 'foo', 'J'
write(*,'(5(A10))') list
write(*,*) list

end program[/fortran]

Gives me this output when compiled with ifort linux 11.1.072:
[bash]         1         2         3         4         5
12345678901234567890123456789012345678901234567890
pear 5 apple foo J
pear 5 apple foo J
pear 5 applefoo J [/bash]


I was hoping that the WRITEing the "list" array with the format specified '5(A10))' would lead to right-hand justification like it does when printing the 'pear', '5', etc. list of strings. However, it appears that the elements of the array were each "allocated" 5 characters ('apple' is the longest word with 5 characters) without right-justification, which wasn't the behaviour I was expecting.

Is there a way for me to achieve right-justification of array items during formatted write? Any workarounds?
0 Kudos
4 Replies
Steven_L_Intel1
Employee
570 Views
Your program is nonstandard - the F2003 rules for the array constructor are that each "ac-value" must be the same length. Intel Fortran has an extension where it picks the longest length. You can't have an array where each element has a different length. To be standard-conforming, you'd have to write:

list = [character(5) :: 'pear', '5', 'apple', 'foo', 'J']

Here's one way to get what you want:

[fortran]program test
implicit none
character(len=:), allocatable, dimension(:) :: list
character(len=*), parameter :: header_10 = ' 1 2 3 4 5'
character(len=*), parameter :: header_1 = '12345678901234567890123456789012345678901234567890'
integer i
!
list = ['pear', '5', 'apple', 'foo', 'J']
write(*,'(A)') header_10
write(*,'(A)') header_1
write(*,'(5(A10))') 'pear', '5', 'apple', 'foo', 'J'
write(*,'(5(A10))') (trim(list(i)),i=1,ubound(list,1))
write(*,*) list
end program[/fortran]
0 Kudos
Alexis_R_
New Contributor I
570 Views
Thanks for your excellent reply.

I had not encountered the construct you use on line 12, which I guess is a one-line implicit loop structure. Does this have a name? I'd like to read up on it!
0 Kudos
Steven_L_Intel1
Employee
570 Views
It's an I/O implied-DO loop, which goes back to F77 at least.
0 Kudos
jimdempseyatthecove
Honored Contributor III
570 Views
>>It's an I/O implied-DO loop, which goes back to F77 at least.
I've used it on Fortran IV (just before F77)
0 Kudos
Reply