Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Fortran Trim() problem

Status
Not open for further replies.

xrayspex1

Technical User
Jun 10, 2008
9
SI
hi all, can anyone maybe explain to me what i am doing wrong with the TRIM function, because it doesn't actually remove any blanks from my string. The code is here:

program trim_err
implicit none
character(30) :: my_string
my_string = ' 123465 '
print *, '|'//my_string//'|'
my_string = trim(my_string)
print *, '|'//my_string//'|'
end program trim_err

This produces the following output (of length 30):
| 123465 |
| 123465 |

Any ideas would be appreciated!
 
Hi xrayspex1

In F77 I usually use LEN_TRIM to remove trailing spaces.
Note the use of "my_string(1:len)", but not "my_string" in the write statement.

Code:
     program trim_err
     implicit none
       character*30 my_string
       integer*2 len
       my_string = ' 123465  '
       len = len_trim(my_string)
       write(*,'(1x,a)') '|'//my_string(1:len)//'|'
     end
 
Code:
program trim_err
   implicit none
   character(30) :: my_string    
   my_string = ' 123465  '    
   print *, '|'//my_string//'|'
   
   ! Since mystring is 30 characters long, you will still get 30 characters
   my_string = trim(my_string)    
   print *, '|'//my_string//'|'
   ! This will remove the traling spaces.  
   print *, '|'//trim(my_string)//'|'
   ! Another way of removing trailing spaces
   print *, '|'//my_string(1:len_trim(my_string))//'|'
   stop
end program trim_err
 
If you need to use the trimmed string a lot, then it is better to pass it to another subroutine. For instance, if your code looks like
Code:
open (10, trim(my_string) // '1.dat', status='old')
open (20, trim(my_string) // '2.dat', status='old')
open (30, trim(my_string) // '3.dat', status='old')
open (40, trim(my_string) // '4.dat', status='old')
...
It would be better if you did
Code:
call openfiles(trim(my_string))
...
subroutine openfiles (prefix)
character*(*) prefix
open (10, prefix // '1.dat', status='old')
open (20, prefix // '2.dat', status='old')
open (30, prefix // '3.dat', status='old')
open (40, prefix // '4.dat', status='old')
...
prefix would be the trimmed string of the correct length.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top