Using a deferred-length character string to read user input

后端 未结 4 539
生来不讨喜
生来不讨喜 2020-12-14 13:18

I would like to use deferred-length character strings in a \"simple\" manner to read user input. The reason that I want to do this is that I do not want to have to declare t

4条回答
  •  旧巷少年郎
    2020-12-14 13:27

    Deferred length character is a Fortran 2003 feature. Note that many of the complicated methods linked to are written against earlier language versions.

    With Fortran 2003 support, reading a complete record into a character variable is relatively straight forward. A simple example with very minimal error handling below. Such a procedure only needs to be written once, and can be customized to suit a user's particular requirements.

    PROGRAM main
      USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INPUT_UNIT
      IMPLICIT NONE
      CHARACTER(:), ALLOCATABLE :: my_string
    
      CALL read_line(input_unit, my_string)
      WRITE (*, "(A)") my_string
      PRINT *, ALLOCATED(my_string), LEN(my_string)
    
    CONTAINS
      SUBROUTINE read_line(unit, line)      
        ! The unit, connected for formatted input, to read the record from.
        INTEGER, INTENT(IN) :: unit
        ! The contents of the record.
        CHARACTER(:), INTENT(OUT), ALLOCATABLE :: line
    
        INTEGER :: stat           ! IO statement IOSTAT result.
        CHARACTER(256) :: buffer  ! Buffer to read a piece of the record.
        INTEGER :: size           ! Number of characters read from the file.
        !***
        line = ''
        DO
          READ (unit, "(A)", ADVANCE='NO', IOSTAT=stat, SIZE=size) buffer
          IF (stat > 0) STOP 'Error reading file.'
          line = line // buffer(:size)
          ! An end of record condition or end of file condition stops the loop.
          IF (stat < 0) RETURN
        END DO
      END SUBROUTINE read_line
    END PROGRAM main
    

提交回复
热议问题