Fortran 90 中的自动宽度整数描述符

Automatic width integer descriptor in fortran 90

我想在 Fortran 90 中使用自动整数宽度描述符。我参考了 Output formatting: too much whitespace in gfortran 这个问题说我可以使用 I0F0,0 作为 "auto" 宽度。 这是我的示例代码(符合 GNU Fortran 编译器):

PROGRAM MAIN
IMPLICIT NONE

INTEGER :: i
REAL :: j

WRITE (*,*) 'Enter integer'
READ (*,100) i
100 FORMAT (I0)

WRITE (*,*) 'Enter real'
READ (*,110) j
110 FORMAT (F0.0)

WRITE (*,100) 'Integer = ',i
WRITE (*,110) 'Real = ',j

END PROGRAM

存在运行时错误(unit = 5, file = 'stdin') Fortran runtime error: Positive width required in format

我是否误解了自动宽度描述符?我应该使用什么选项?

使用I0 指定允许输出的最小字段宽度。对于输入,不允许I0

来自 Fortran 2008,10.7.2.1 (6)(我的重点):

On output, with I, B, O, Z, F, and G editing, the specified value of the field width w may be zero. In such cases, the processor selects the smallest positive actual field width that does not result in a field filled with asterisks. The specified value of w shall not be zero on input.

对于输入,没有明确的 I0 替代方案,但作为 agentp 的评论,列表定向输入 (read(*,*)) 很简单,很可能适合您的需要。如果不是,那么您可以研究对作为字符变量读入的行进行更一般的解析。您可以 find 后者的示例。

除了@francescalus 和@agentp 的回答之外,请注意格式标签,例如100 FORMAT (I0) 应该避免。

相反,只需将 format 包含在 read 中,例如如果您想读取最多 8 个字符宽的整数,READ(*,'(I8)') i.

如果您有一个非常冗长的格式或您在多行代码中重复使用的格式,请将其保存在一个字符串中:

character :: form*64
real      :: r1, r2

form = '(es13.6)'  ! e.g. 9.123456e+001

.
.
.

WRITE (*,*) 'Enter a number'
READ (*, form) r1
WRITE (*,*) 'Enter another number'
READ (*, form) r2