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

Question about reading data

Zhanghong_T_
Novice
999 Views
Hi,
I am trying to read a text file with the following data:
1 25 2 24 3 23 4 22 7 19 10 16 13
5 6
21 20
8 9
18 17
11 12
15 14


I defined an array:
integer list(7,25)
and then initialized it to zero.
Now I wish the data be filled into the front ofevery line of thearray, how should I design the read program?
Thanks,
Zhanghong Tang
0 Kudos
8 Replies
h-faber
Beginner
999 Views
Does your textfile always look like your example or do you have variable number of data?
0 Kudos
Zhanghong_T_
Novice
999 Views

Hi,

Thank you for your reply. Just as you say, the number of data in every line is unknown, so...

0 Kudos
Zhanghong_T_
Novice
999 Views

When I using the read statement as follows,

read(1,*)data

it will always turn to the next line, can I read several number in a line with several read statement? Just as

read(1,*)(data(i),i=1,n)

But I don't know the value of n, how should I do?

Thanks,

Zhanghong Tang

0 Kudos
anthonyrichards
New Contributor III
999 Views

1) Read each record as a character string

CHARACTER(500)

READ(1,*) STRING

2)Get the string's length

LENGTH=LEN_TRIM(STRING)

2) count the spaces in the string: this is one less than the number of integer data items

ISTART=1
DO J=1,25
ISPACE=INDEX( STRING(ISTART:LENGTH), ' ')
IF(ISPACE.EQ.0) EXIT
ISTART=ISPACE+1
ENDDO

3) Use in internal read, selecting to read in this number+1 items

READ(STRING(1:LENGTH),*) (DATA(I),I=1,NUMBER)

0 Kudos
anthonyrichards
New Contributor III
999 Views

The following code assumes that ther will be at elast one number in a record.

1) Read each record as a character string

CHARACTER(500)
INTEGER(4) I, NUMBER, ISTART, ISPACE

READ(1,*) STRING

2)Get the string's length

LENGTH=LEN_TRIM(STRING)

2) count the spaces in the string: this is one less than the number of integer data items

ISTART=1
NUMBER=0
DO J=1,25'
! EXIT IF SPACE NOT FOUND FROM 'ISTART' TO THE END
ISPACE=INDEX( STRING(ISTART:LENGTH), ' ')
IF(ISPACE.EQ.0) EXIT
ISTART=ISPACE+1
NUMBER=NUMBER+1
ENDDO
NUMBER=NUMBER+1

3) Use in internal read, selecting to read in this number+1 items

READ(STRING(1:LENGTH),*) (DATA(I),I=1,NUMBER)

I have not tested it, but it can be made to work.

0 Kudos
Zhanghong_T_
Novice
999 Views
Thank you very much! Now I got it.
Thanks,
Zhanghong Tang
0 Kudos
anthonyrichards
New Contributor III
999 Views

I forgot to include a line of code

STRING = ADJUSTL(ADJUSTR(" "))

(or similar) to initialise the STRING variable to all blanks BEFORE each READ, otherwise it will contain stuff from a previous READ which will screw things up eventually, if the next record is shorter than the last.

0 Kudos
Les_Neilson
Valued Contributor II
999 Views

Even simpler STRING = " " will do

Les

0 Kudos
Reply