Convert integers to strings to create output filenames at run time

前端 未结 9 2007
小鲜肉
小鲜肉 2020-11-22 02:47

I have a program in Fortran that saves the results to a file. At the moment I open the file using

OPEN (1, FILE = \'Output.TXT\')

However,

9条回答
  •  粉色の甜心
    2020-11-22 03:53

    you can write to a unit, but you can also write to a string

    program foo
        character(len=1024) :: filename
    
        write (filename, "(A5,I2)") "hello", 10
    
        print *, trim(filename)
    end program
    

    Please note (this is the second trick I was talking about) that you can also build a format string programmatically.

    program foo
    
        character(len=1024) :: filename
        character(len=1024) :: format_string
        integer :: i
    
        do i=1, 10
            if (i < 10) then
                format_string = "(A5,I1)"
            else
                format_string = "(A5,I2)"
            endif
    
            write (filename,format_string) "hello", i
            print *, trim(filename)
        enddo
    
    end program
    

提交回复
热议问题