user3705273
user3705273

Reputation: 335

Automatic width integer descriptor for input with Fortran

I wanted to use an automatic integer width descriptor in Fortran. I referred to Output formatting: too much whitespace in gfortran

This question says that I can use I0 and F0.0 for "auto" width. Here is my sample code (complied with GNU Fortran Compiler):

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

There is runtime error

(unit = 5, file = 'stdin')
Fortran runtime error: Positive width required in format

Am I mis-understanding the auto width descriptor? What option should I use?

Upvotes: 5

Views: 3405

Answers (2)

Jeff Irwin
Jeff Irwin

Reputation: 1051

In addition to @francescalus 's and @agentp 's answers, be aware that format labels, e.g. 100 FORMAT (I0) should be avoided.

Instead, simply include the format within the read, e.g. if you wanted to read an integer that is up to 8 characters wide, READ(*,'(I8)') i.

If you have a very lengthy format or a format that you re-use in several lines of code, save it in a character string:

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

Upvotes: 0

francescalus
francescalus

Reputation: 32406

Using I0 to specify a minimal field width is allowed for output. For input, I0 is not allowed.

From Fortran 2008, 10.7.2.1 (6) (my emphasis):

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.

There is no clear alternative to I0 for input, but as agentp comments, list-directed input (read(*,*)) is simple and may well be suitable for your needs. If it isn't then you can look into more general parsing of lines read in as character variables. You can find examples of this latter.

Upvotes: 7

Related Questions