Fortran: `READ(*,*)` != Command-line arguments. How to use command line arguments?

后端 未结 1 485
终归单人心
终归单人心 2020-12-06 11:16

GCC version 4.6

The Problem: To find a way to feed in parameters to the executable, say a.out, from the command line - more specificall

相关标签:
1条回答
  • 2020-12-06 11:25

    If you want to get the arguments fed to your program on the command line, use the (since Fortran 2003) standard intrinsic subroutine GET_COMMAND_ARGUMENT. Something like this might work

    PROGRAM MAIN  
         REAL(8)    :: A,B
         integer :: num_args, ix
         character(len=12), dimension(:), allocatable :: args
    
         num_args = command_argument_count()
         allocate(args(num_args))  ! I've omitted checking the return status of the allocation 
    
         do ix = 1, num_args
             call get_command_argument(ix,args(ix))
             ! now parse the argument as you wish
         end do
    
         PRINT*, A+B, COMMAND_ARGUMENT_COUNT()
    END PROGRAM MAIN
    

    Note:

    • The second argument to the subroutine get_command_argument is a character variable which you'll have to parse to turn into a real (or whatever). Note also that I've allowed only 12 characters in each element of the args array, you may want to fiddle around with that.
    • As you've already figured out read isn't used for reading command line arguments in Fortran programs.

    Since you want to read an array of real numbers, you might be better off using the approach you've already figured out, that is reading them from the terminal after the program has started, it's up to you.

    0 讨论(0)
提交回复
热议问题