Tuesday, 4 December 2007

Converting integers to strings in Fortran

Assisted by this page, I present the result:

character(11), parameter :: fstart = "Xfiles/Xbin"
character(4), parameter :: fend =".txt"
character(3) :: fnum
character(18) :: fname
integer :: blob

blob = 2
write (fnum,1000) blob
1000 format(I3)
fname = fstart//trim(adjustl(fnum))//fend

The double slash "//" concatenates strings. The strange form of the write command (rather than just char(blob) gives you the value of blob as a character, rather than the ascii character for that number. The adjustl(fnum) function moves the contents of string "fnum" to the left, to leave all trailing blanks to the right. The call to trim(string) then removes the trailing blanks. This is necessary to avoid spaces appearing in "fname" if the value of blob is only 2 digits or less, since I defined "fnum" to be three characters long.


Michael said...

My dear old cake, /I/ see code like that and think "so why the hell would anyone code in Fortran?!"

So, why the hell...?

Ali said...

You make a fair point, Monsieur, but eet is the NAG library and zee compili-ness of zee code zat made me do eet. Plus, I have forgotten all my C skillz. Cobol? ;-)