Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29396 Обсуждение

Question about reading data

Zhanghong_T_
Новичок
1 213Просмотр.
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 баллов
8 Ответы
h-faber
Начинающий
1 213Просмотр.
Does your textfile always look like your example or do you have variable number of data?
Zhanghong_T_
Новичок
1 213Просмотр.

Hi,

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

Zhanghong_T_
Новичок
1 213Просмотр.

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

anthonyrichards
Новый участник III
1 213Просмотр.

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)

anthonyrichards
Новый участник III
1 213Просмотр.

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.

Zhanghong_T_
Новичок
1 213Просмотр.
Thank you very much! Now I got it.
Thanks,
Zhanghong Tang
anthonyrichards
Новый участник III
1 213Просмотр.

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.

Les_Neilson
Ценный участник II
1 213Просмотр.

Even simpler STRING = " " will do

Les

Ответить