Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fortran trim or adjustl not working while using twice

I am trying to use trim/adjustl for the following code. It seems that I'm getting either X_eq_ 10.0.dat or X_eq_10.0 .dat as the output file's name where I'm expecting it to be X_eq_10.0.dat (no blank space). Any remedy?

           Program Test
           double precision:: X
           character (len=10) :: tag
           character (len=100) :: outfile

           X=10.0

           write(tag,'(f10.1)') X
           print*,'tag=',tag

           outfile='X_eq_'//trim(tag)//'.dat'
           print*,'Output file: ',outfile

           outfile='X_eq_'//trim(tag)//trim('.dat')
           print*,'Output file: ',outfile

           outfile='X_eq_'//adjustl(trim(tag))//adjustl(trim('.dat'))
           print*,'Output file: ',outfile

           End Program Test

I have used gfortran as the compiler.

like image 314
hbaromega Avatar asked Mar 04 '23 10:03

hbaromega


2 Answers

What you want is:

outfile='X_eq_'//trim(adjustl(tag))//'.dat'

adjustl shifts the characters left, leaving trailing blanks, so you need to trim that result. It does no good to do trim(tag) as that is already right-adjusted. Lastly, '.dat' doesn't need any processing.

like image 158
Steve Lionel Avatar answered Mar 06 '23 21:03

Steve Lionel


In

write(tag,'(f10.1)') X

we say that we want tag to be of width 10 with one digit in the fractional part. With the one decimal symbol that leaves us 8 places before the decimal: there will be blank padding beyond the (optional) sign.

This is why we see lots of blanks in outfile='X_eq_'//trim(tag)//'.dat'.

We can avoid this either with adjustl as noted in the question or another answer, or by using 0 in the edit descriptor:

write(tag,'(F0.1)') X

The F0.d form makes the field width the smallest appropriate field with: without leading blanks.

When tag has length 100 there will still be (lots of) trailing blanks, so a trim will be necessary.

Further, there are even ways to avoid using an intermediary such as tag without using trim.

like image 26
francescalus Avatar answered Mar 06 '23 23:03

francescalus