Reputation: 617
I'm working with a fortran program that reads a lot of data from a file and writes it back in a different format.
The code I'm using to read the data is this:
10 read(10,*,err=11,end=20) f,time(i),(a(i,j),j=1,14)
...
goto 10
11 i=i+1
goto 10
It works, but only when the input file is correct. But some lines are like this:
"2014-04-28 07:51:18.9",2705,-8.42144,6.623851,0.4654102,20.99942,"NAN","NAN",0,0,0,0,-9.0605,5.8855,0.4135,21.39728
When this happens I lose every value in the line after the NAN. Is there a way to read the other values?
It's possible to read every value as a string and then convert them to doubles? I know very little about fortran and I need to fix it quickly. Rewriting everything in C could take too much time.
Upvotes: 0
Views: 2289
Reputation: 617
I got it working. Here is the code:
10 read(10,'(a)',err=16,end=20) linha
linha=trim(adjustl(linha))
pos1=1
n2=0
DO
pos2 = INDEX(linha(pos1:), ",")
IF (pos2 == 0) THEN
n2 = n2 + 1
strings(n2) = linha(pos1:)
EXIT
END IF
n2 = n2 + 1
strings(n2) = linha(pos1:pos1+pos2-2)
pos1 = pos2+pos1
END DO
f=strings(1)
read(strings(2),*) time(i)
j=1
11 read(strings(j+2), *,err=12) a(i,j)
j=j+1
IF (j > 14) THEN
goto 13
END IF
goto 11
12 a(i,j)=9999
j=j+1
goto 11
13 IF (a(i,6)==9999) THEN
goto 14
END IF
pp=1000.
c1=0.622
c2=1.-c1
rv=461.5
e=0.001*a(i,6)*rv*(a(i,4)+273.15)
a(i,6)=1000*e*c1/(100*pp-c2*e)
14 IF (a(i,5)==9999) THEN
goto 15
END IF
mimol=a(i,5)/44
a(i,5)=mimol*83.14*(a(i,4)+273.15)/pp
15 i=i+1
n=i-1
if (i.gt.nmax) goto 20
goto 10
16 i=i+1
goto 10
Thanks for the help.
Upvotes: 0
Reputation: 29391
Yes, you can read the entire line into a string. Then parse the string and replace the "NAN" with some special numeric value such as a large negative value. The intrinsic functions can help, e.g., index
. Then use an "internal read" to read from the string into the numeric variables.
See: Reading comment lines correctly in an input file using Fortran 90, Reading format in Fortran 90 and Prevent FORTRAN from closing when a character is inputed instead of a number
Upvotes: 3