Search code examples
fortranstring-length

How can I know the length of user input with trailing whitespaces in Fortran?


I want to know the length of one line of the user input in Fortran. Since that input can contain some trailing whitespaces, LEN_TRIM does not give the correct answer.

program test

implicit none
character(len=100) :: s

read(*, '(a)') s
write(*, '(i0)') len_trim(s)

end program test

example inputs and outputs:

input: Hello World!

output: 12

expected output: 15

input: (5 spaces)

output: 0

expected output: 5


Solution

  • Read the input one character at a time and count the number read from STDIN.

    program foo
      character(len=100) s
      integer i
      i = 1
      do
          read(*,'(A1)',eor=10,advance='no') s(i:i)
          i = i + 1
      end do
    10 print *, i - 1  ! Minus for '\n'
    end program foo
    

    TRIM and LEN_TRIM will still get rid of trailing whitespace. You can test that s(i:i) == ' ' and then set it to some printable character.