How to read comma delimited data file if some data include spaces

喜你入骨 提交于 2020-01-13 06:55:29

问题


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!" ?


回答1:


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.



来源:https://stackoverflow.com/questions/15485531/how-to-read-comma-delimited-data-file-if-some-data-include-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!