Pergunta

I am trying to read a data file which uses comma as delimiter as shown below

IPE 80,764,80.14,8.49
IPE 100,1030,171,15.92

However If I read using

READ(1,*) var1, var2, var3, var4

It reads IPE and 80 as different data. In other words it counts both commas and spaces as delimiter but I don't want this. How can I tell to my program "hey spaces are not delimiter only commas!" ?

Foi útil?

Solução

One possibility would be to read in the entire line into a string buffer, and look for (some of) the delimiters yourself. Assuming that similar to your example, only the first column contains with whitespaces, you could do like:

program test
  implicit none

  character(1024) :: buffer
  character(20) :: var1
  integer :: pos, var2
  real :: var3, var4

  read(*,"(A)") buffer
  pos = index(buffer, ",")
  var1 = buffer(1:pos-1)
  read(buffer(pos+1:), *) var2, var3, var4
  print *, var1, var2, var3, var4

end program test

This way, you split that part of the string manually which is affected by the spaces, and everything else after it you conviniently read via the read statement. If not just the first but also other fields can contain whitespaces, it is easy to extend the example above to look for all the necessary delimiters in the buffer via the index() function.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top