Reading a string with spaces in Fortran

Gautam picture Gautam · Jun 12, 2011 · Viewed 35.7k times · Source

Using read(asterisk, asterisk) in Fortran doesn't seem to work if the string to be read from the user contains spaces. Consider the following code:

    character(Len = 1000) :: input = ' '
    read(*,*) input

If the user enters the string "Hello, my name is John Doe", only "Hello," will be stored in input; everything after the space is disregarded. My assumption is that the compiler assumes that "Hello," is the first argument, and that "my" is the second, so to capture the other words, we'd have to use something like read(,) input1, input2, input3... etc. The problem with this approach is that we'd need to create large character arrays for each input, and need to know exactly how many words will be entered. Is there any way around this?? Some function that will actually read the whole sentence, spaces and all? Many thanks!

Answer

Rook picture Rook · Jun 12, 2011
  character(100) :: line

  write(*,'("Enter some text: ",\)')
  read(*,'(A)') line
  write(*,'(A)') line

  end

... will read a line of text of maximum length 100 (enough for most practical purposes) and write it out back to you. Modify to your liking.