Fortran:`READ(*,*)`!=命令行参数。如何使用命令行参数? [英] Fortran: `READ(*,*)` != Command-line arguments. How to use command line arguments?

查看:1480
本文介绍了Fortran:`READ(*,*)`!=命令行参数。如何使用命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC版本4.6

问题:要找到一种方法来向可执行文件提供参数,请说

The Problem: To find a way to feed in parameters to the executable, say a.out, from the command line - more specifically feed in an array of double precision numbers.

尝试:

PROGRAM MAIN  
     REAL(8)    :: A,B  
     READ(*,*) A,B
     PRINT*, A+B, COMMAND_ARGUMENT_COUNT()
END PROGRAM MAIN

执行 -

$ gfortran test.f
$ ./a.out 3.D0 1.D0

这没有用。有一点灵魂寻找,发现

This did not work. On a bit of soul-searching, found that

$./a.out
3.d0,1.d0
   4.0000000000000000                0

可以工作,但第二行是输入提示,在单行中完成这一目标的目标没有实现。此外, COMMAND_ARGUMENT_COUNT()表明输入到输入提示中的数字不会真正计为命令行参数,与PERL不同。

does work, but the second line is an input prompt, and the objective of getting this done in one-line is not achieved. Also the COMMAND_ARGUMENT_COUNT() shows that the numbers fed into the input prompt don't really count as 'command line arguments', unlike PERL.

推荐答案

如果要在命令行上获取输入到程序的参数,请使用子例程 GET_COMMAND_ARGUMENT 。类似这样的工作

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

注意:


  • 子程序的第二个参数 get_command_argument 是一个字符变量,你必须解析成一个真实的(或任何)。还要注意,我只允许在 args 数组的每个元素中有12个字符,你可能想要解决这个问题。

  • 因为你已经知道 read 不用于在Fortran程序中读取命令行参数。

  • 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.

这篇关于Fortran:`READ(*,*)`!=命令行参数。如何使用命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆