Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a string with spaces in Fortran

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!

like image 980
Gautam Avatar asked Jun 12 '11 01:06

Gautam


People also ask

How do I print an empty line in Fortran?

We can either print blank records or explicitly add a newline character. NEW_LINE('a') is likely to have an effect like ACHAR(10) or CHAR(10,KIND('a')) . NEW_LINE('a') could also be used in the format string but this doesn't seem to add much value beyond slash editing.

What is Fortran trim?

8.275 TRIM — Remove trailing blank characters of a string Removes trailing blank characters of a string.

What is index in Fortran?

The INDEX function returns the starting position of a substring within a string.


2 Answers

  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.

like image 125
Rook Avatar answered Oct 17 '22 16:10

Rook


Instead of read(*, *), try read(*, '(a)'). I'm no Fortran expert, but the second argument to read is the format specifier (equivalent to the second argument to sscanf in C). * there means list format, which you don't want. You can also say a14 if you want to read 14 characters as a string, for example.

like image 29
John Zwinck Avatar answered Oct 17 '22 15:10

John Zwinck