fortranfortran2008

Reading integers of unknown width in Fortran


I am trying to read the integers in this line:

# 14 14 10

in Fortran 2008.

I attempted to use this code:

read(21, "(A, I,I,I)") garbage, a, b, c

but this is not standard conforming. Intel Fortran issues a warning "Fortran 2008 does not allow this edit descriptor. [I]" and other qeustions explain this problem: Nonnegative width required in format string Error: Nonnegative width required in format string at (1)

How do I properly read the integers of unknown width using Fortran 2008? I can not simply specify I2, because I do not know the width of the integer in advance.


Solution

  • As I hinted in the comments you can read items like this easily with the list directed I/O. The compiler then itself identifies which characters belong to each item in the input list and parse them. The items can be separated by spaces, commas or also a newline.

    read(21,*) garbage, a, b, c
    

    This is the most common way to read stuff interactively, but is also useful for parsing lists in data files (CSV and similar).

    If on of the numbers were not present in the input record (line in a text file), the reading would continue on the next record.