Read scientific formatted numbers from txt

后端 未结 2 607
面向向阳花
面向向阳花 2021-01-24 18:49

I would like to read and store scientific formatted numbers from a txt file, which is formatted and the numbers are separated by tabulator.

This is what I have so far:

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-24 19:34

    Yes, your format is not good for the data you show. Better one should be like that read(99,'(6(E11.4,X))') myData(i,:).

    However, I am not sure if you really need to use format at your reading at all.

    Following example pretty close to what you are trying to do, and it is working bot with and without format.

    program readdata
      implicit none
      real, allocatable :: myData(:,:)
      real              :: myLine
      integer           :: i, j, myRow, myColumn
      character(len=30) :: myFileName
      character(len=30) :: myFormat
    
      myFileName='data.dat'
    
      open(99, file=myFileName)
      write(*,*)'open data file'
      read(99, *) myRow
      read(99, *) myColumn
    
      allocate(myData(myRow,myColumn))
    
      do i=1,myRow
        read(99,*) myData(i,:)
        !read(99,'(6(E11.4,X))') myData(i,:)
        print*, myData(i,:)
      enddo
    
      close(99)
    
    end program readdata
    

    To test, I assumed that you have rows and columns always in the file, as you give, so my test data was following.

    2
    6
    2.9900E-35  2.8000E-35  2.6300E-35  2.4600E-35  2.3100E-35  2.1600E-35
    2.9900E-35  2.8000E-35  2.6300E-35  2.4600E-35  2.3100E-35  2.1600E-35
    

    If you are really interested to read your files with a format and if the number of columns are not constant you may need a format depending on a variable, please see related discussions here.

提交回复
热议问题