Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

internal write

alexismor
Beginner
676 Views
Hi everyone,

I'm trying to convert an integer into a string so that I can use this integer in the filename of a file that my program writes results to.

This is how I'm doing it:

integer :: prox !prox is between 0 and 99
character*100 :: name
...
write(name,'(i2)')prox
name='p'//trim(name)//'.dat'

My problem is that sometimes prox has only one digit, sometimes it has two. In the case when it has only one digit, the above produces a filename like this: (say prox=8)

p 8.dat

I want this to be p8.dat. I guess that I can always use if statements to descriminate between both cases, like so:

if (prox<10) then
write(name,'(i1)')prox
else
write(name,'(i2)')prox
endif

Is there a more elegant way to do this?

Thanks,

Alexis
0 Kudos
4 Replies
Steven_L_Intel1
Employee
676 Views
Use '(I0)' as the format.
0 Kudos
emc-nyc
Beginner
676 Views
You've two alternatives:

use i0 format, as suggested by Steve. This will give only the number of digits required, i.e., it will write 1 as "1", 10 as "10", 100 as "100", etc.

Alternatively, if you want them all to have the same length, use a format like I2.2. This will write leading zeros, i.e., it will write 1 as "01" and 10 as "10". It will, however, write 100 as "**". (in which case you could use i3.3 or i4.4 or i99.99 or whatever)

In your case

using this statement:
write(name,'("p",i0,".dat")') prox

when prox is 8, name will be 'p8.dat'

when prox is 10, name will be 'p10.dat'

Using this one

write(name,'("p",i2.2,".dat")') prox

when prox is 8, name will be 'p08.dat'
when prox is 10, name will be 'p10.dat'
0 Kudos
alexismor
Beginner
676 Views
Thanks steve and emc-nyc, that's exactly what I needed to know.

Cheers,

Alexis
0 Kudos
anthonyrichards
New Contributor III
676 Views

How about

character*100 filenamenoextension
character*10 p
integer i
write(p,'(i10)') i
filename=TRIM(ADJUSTL(filenamenoextension))//TRIM(ADJUSTL(p))//'.ext'

? Just define 'p' as long enough to take the largest likely integer value and strip off unwanted blanks before use. If you use an explicit format such as the one shown above, make sure thecharacter length for 'p' is not shorter than the largest integer likely to be written to it or your program will crash.

0 Kudos
Reply