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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With