The following code reads a user input string of indefinite length. Keep in mind that this requires a compiler that supports deferred character(len = :) strings: character(len = :) . Delayed string strings were introduced in Fortran 2003.
program test use iso_fortran_env, only : IOSTAT_EOR implicit none integer :: io_number character(len = 1) :: buffer character(len = :), allocatable :: input, output input = "" print *, "Please input your message." do read(unit = *, fmt = '(a)', advance = "no", iostat = io_number) buffer select case (io_number) case(0) input = input // buffer case(IOSTAT_EOR) exit end select end do allocate(character(len=(len(input))) :: output) ! Now use "input" and "output" with the ciphering subroutine/function. end program test
Description
The idea is to read one character at a time, looking for a write termination condition (eor). The eor condition is triggered by pressing the return button. The "iostat" option can be used to search for eor. The value returned by "iostat" is equal to the integer constant "IOSTAT_EOR" located in the iso_fortran_env module:
use iso_fortran_env, only : IOSTAT_EOR
We declare a string of characters with a deferred length to capture user input of unknown length:
character(len = :), allocatable :: input
In the "read" instruction, advance = "no" allows you to read several characters at a time. The size of the "buffer" determines the number of characters that need to be read (1 in our case).
read(unit = *, fmt = '(a)', advance = "no", iostat = io_number) buffer
If "iostat" returns "0", then there were no errors and no. In this case, the character "buffer" should be added to the string "enter". Ultimately, this step allocates a "new" input, the size of which is the "old" input + buffer character. The newly assigned input contains characters from the old input + buffer character.
select case (io_number) case(0) input = input // buffer
If "iostat" returns eor, exit the do loop.
case(IOSTAT_EOR) exit