Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

how to read in the same line

horst_haas_a_itp_fzk
2,288 Views
Hello,
say I have an input data file, which is not created by myself. In such an input file I want to read several times in the same line. How can I do this?

Exampleinput_file

cx 12 3
cy 12

my fortran code
implicit none
character input_ch
integer cx_1,cx_2,cx_3,cy_1,cy_2

open(unit=9,file='input_file',action='read',status='old')

read(9,*) input_ch
if (input_ch.eq.'cx') then
read(9,*) cx_1,cx_2,cx_3
! do many things after
end if
...

See, for each line I need translate the meanings of the numbers according the first character. In this example, if the first character is cx, then the next three numbers are inputed as cx_1, cx_2 and cx_3.

The problem is the second read inside if-clause automatically jumps to the next line and gets an error (to meet cy in the next line). How can I solve this problem? Thank you in advance.

0 Kudos
4 Replies
Les_Neilson
Valued Contributor II
2,288 Views
The "usual" method is for the first read to be into a character string.
You then parse the string for "cx" etc and do an appropriate second read from that character string into you variables. See the help on "InternalFiles" and Internal I/O


character(len=80) :: astring
read(9,'(a)') astring
if (astring(1:2) == "cx") then
read(astring(3:) , *) cx_1, cx_2, cx_3
else if (astring(1:2 == "cy") then

etc

By the way in the sample code shown you have input_ch as character - this means it is ONE character in length and so would match anything beginning with "c"

Les
0 Kudos
horst_haas_a_itp_fzk
2,288 Views
Thanks for very quick reply. I have tried and it works fine.
Have a nice weekend!
0 Kudos
dboggs
New Contributor I
2,288 Views
You should also have a look at the BACKSPACE statement.
0 Kudos
abhimodak
New Contributor I
2,288 Views
Alternatively, you may want to use "ADVANCE=NO".

Abhi


===

Program Test_Advance

Implicit None

Character(2) :: Name
Integer :: io
Real :: a, b, c
Real :: d, e

io = 0
Open(91, File="Input.inp", Form='Formatted', Status='Old',IOSTAT=io)
Rewind(91)
do while (io == 0)
Read(91,"(A)",Advance='NO',IOSTAT=io) Name
if (io == 0) then
Select Case (Trim(Name))
Case ('CX')
Read(91,*) a, b, c
Case ('CY')
Read(91,*) d, e
Case Default
io = -11
End Select
endif
end do
Close(91)

End Program Test_Advance


===
0 Kudos
Reply