Number Parsing in Co-array Fortran

In Co-array Fortran, number parsing is typically handled using internal read statements or intrinsic functions. Here’s how to parse numbers from strings:

program number_parsing
    use iso_fortran_env, only: real64, int64
    implicit none

    real(real64) :: f
    integer(int64) :: i, d, u, k
    character(len=20) :: str
    integer :: ios

    ! Parsing float
    str = "1.234"
    read(str, *, iostat=ios) f
    if (ios == 0) then
        print *, f
    else
        print *, "Error parsing float"
    end if

    ! Parsing integer
    str = "123"
    read(str, *, iostat=ios) i
    if (ios == 0) then
        print *, i
    else
        print *, "Error parsing integer"
    end if

    ! Parsing hexadecimal
    str = "0x1c8"
    read(str(3:), '(Z20)', iostat=ios) d
    if (ios == 0) then
        print *, d
    else
        print *, "Error parsing hexadecimal"
    end if

    ! Parsing unsigned integer
    str = "789"
    read(str, *, iostat=ios) u
    if (ios == 0) then
        print *, u
    else
        print *, "Error parsing unsigned integer"
    end if

    ! Parsing integer (similar to Atoi)
    str = "135"
    read(str, *, iostat=ios) k
    if (ios == 0) then
        print *, k
    else
        print *, "Error parsing integer"
    end if

    ! Demonstrating error handling
    str = "wat"
    read(str, *, iostat=ios) k
    if (ios /= 0) then
        print *, "Error: Invalid syntax"
    end if

end program number_parsing

In this Co-array Fortran example:

  1. We use the iso_fortran_env module to ensure we have 64-bit real and integer types.

  2. For parsing floating-point numbers and integers, we use internal read statements. The * format specifier allows for free-format input.

  3. For hexadecimal parsing, we use a specific format specifier Z20.

  4. Error handling is done by checking the iostat variable after each read operation.

  5. Co-array Fortran doesn’t have a direct equivalent to ParseUint, so we use a regular integer read for the unsigned integer example.

  6. There’s no direct equivalent to Atoi, but using a regular integer read accomplishes the same thing.

  7. The last example demonstrates error handling when trying to parse an invalid input.

To run this program:

$ gfortran -o number_parsing number_parsing.f90
$ ./number_parsing

This will compile and run the program, outputting the parsed numbers or error messages.

Co-array Fortran’s approach to number parsing is more verbose than some other languages, but it provides fine-grained control over the parsing process and error handling.