Reputation: 107
i have one data file in which data are filled in this manner
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
.
.
.
.
.
91 92 93 94 95 96 97 98 99 100
i want to store this data in a matrix of (10,10) this is my program
program test
integer j,n,m
character,dimension(10,10) ::text
character*50 line
open(unit=3,file="tmp.txt",status='old')
n=1
read(3,"(a50)"),line
read(line,*,end=1),(text(1,i),i=1,10)
1 read(3,"(a50)",end=3),line
n=n+1
read(line,*,end=1)(text(n,i),i=i,10)
3 close(3)
end program test
but i am not getting correct values.
Upvotes: 0
Views: 1541
Reputation: 2917
Assuming you are happy with having the numbers stored as integers, the simplest way is to do it like this:
PROGRAM read_data
integer :: i
integer :: numbers(39,39)
character(10) :: infile = "data.dat"
character(10) :: outfile = "output.dat"
open(1,file=infile)
open(2,file=outfile)
do i=1,39
read(1,*) numbers(i,1:39)
end do
!write output to check
do i=1,39
write(2,'(39I5)') numbers(i,1:39)
end do
close(1)
close(2)
END PROGRAM
I wouldn't recommend using strings to store variables of any kind as Fortran is not very good at string handling. If you at some point need to use your data as strings, write it to a string variable like you would write to a file:
write(my_string,'(I5)') numbers(1,1)
Edit: changed code to read in 39x39 size array instead of 10x10.
Upvotes: 5
Reputation: 50927
I don't think doing the reading into a string first and then trying to parse that is the way to go; just let Fortran to break the space-delimited line up into character strings for you. Also note that you want your character array to be an array of something-length character strings, not just of characters:
program test
character(len=3),dimension(10,10) ::text
character(len=7), parameter :: filename="tmp.txt"
integer :: i,j
integer :: nlines
open(unit=3,file=filename)
do i=1,10
write(3,fmt="(10(i3,1x))"), (10*(i-1)+j, j=1,10)
enddo
close(unit=3)
open(unit=4,file=filename,status='old')
do i=1,10
read(4,*,end=1), (text(i,j),j=1,10)
enddo
1 nlines = i
close(unit=4)
print *,' Read in character array: '
do i=1,nlines-1
print "(10('<',a,'>',1x))", (trim(text(i,j)), j=1,10)
enddo
end program test
Running this gives
$ ./test
Read in character array:
<1> <2> <3> <4> <5> <6> <7> <8> <9> <10>
<11> <12> <13> <14> <15> <16> <17> <18> <19> <20>
<21> <22> <23> <24> <25> <26> <27> <28> <29> <30>
<31> <32> <33> <34> <35> <36> <37> <38> <39> <40>
<41> <42> <43> <44> <45> <46> <47> <48> <49> <50>
<51> <52> <53> <54> <55> <56> <57> <58> <59> <60>
<61> <62> <63> <64> <65> <66> <67> <68> <69> <70>
<71> <72> <73> <74> <75> <76> <77> <78> <79> <80>
<81> <82> <83> <84> <85> <86> <87> <88> <89> <90>
<91> <92> <93> <94> <95> <96> <97> <98> <99> <100>
Upvotes: 4