Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format: add trailing spaces to character output to left-justify

How do you format a string to have constant width and be left-justified? There is the Aw formatter, where w denotes desired width of character output, but it prepends the spaces if w > len(characters), instead of appending them.

When I try

44 format(A15)
   print 44, 'Hi Stack Overflow'

I get

>        Hi Stack Overflow<

instead of

>Hi Stack Overflow        <

Is there any simple Fortran formatting solution that solves this?

like image 560
Daniel R. Livingston Avatar asked Mar 08 '23 09:03

Daniel R. Livingston


2 Answers

As noted in the question, the problem is that when a character expression of length shorter than the output field width the padding spaces appear before the character expression. What we want is for the padding spaces to come after our desired string.

There isn't a simple formatting solution, in the sense of a natural edit descriptor. However, what we can do is output an expression with sufficient trailing spaces (which count towards the length).

For example:

print '(A50)', 'Hello'//REPEAT(' ',50)

or

character(50) :: hello='Hello'
print '(A50)', hello

or even

print '(A50)', [character(50) :: 'hello']

That is, in each case the output item is a character of length (at least) 50. Each will be padded on the right with blanks.

If you chose, you could even make a function which returns the extended (left-justified) expression:

print '(A50)', right_pad('Hello')

where the function is left as an exercise for the reader.

like image 128
francescalus Avatar answered Mar 12 '23 15:03

francescalus


To complete @francescalus excellent answer for future reference, the proposed solution also works in case of allocatables in place of string literals:

character(len=:), allocatable :: a_str

a_str = "foobar"

write (*,"(A,I4)") a_str, 42
write (*,"(A,I4)") [character(len=20) :: a_str], 42

will output

foobar  42
foobar                42
like image 24
dev-zero Avatar answered Mar 12 '23 15:03

dev-zero