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

Read a string like read a file?

haitao
Novice
614 Views
I have a old program reading a text file line by line. the code is like this:
character*80 line
open (4, file = 'myfile.txt')
do while (n .eq. 0)
read(4,'(80a)',end = 9999) line
callmysub(line)!do something for line
end do
9999
n = -1
Now, a long string is passed here instead of myfile.txt. I want to do this:
character*(80) line
character*(10000)input_str
do while (n .eq. 0)
read(input_str, '(80a)',end = 9999) line
callmysub(line)!do something for line
end do
9999
n = -1
The problem is it always start to readat beginning of the input_str, then the line is always the same.
Is there any way to control the position of read like read a file?
Thanks.
hhtlib
0 Kudos
2 Replies
anthonyrichards
New Contributor III
614 Views

You need to keep track of where you are in read input_str after each read.

You also should initialise 'line' to blanks before each read, otherwise reading the last section that is not exactly 80 characters long will leave characters from the previous read in the locations that are not overwritten. One suggestion is, if 'numchars' is the number of characters to be read each time:

integer numchars, len_input, numreads, iread, istart, iend

character*80 line, blankline

blankline=adjustl(adjustr(blankline))

numchars=80

len_input=len_trim(input_str)

numreads=(len_input+numchars-1)/numchars

istart=1

iend=numchars

if(numreads>0) then

do iread=1,numreads

line=blankline

read(input_str(istart:iend), '(80a)',end = 9999) line

callmysub(line)!do something for line

istart=istart+numchars

iend=iend+numchars

end do
endif
0 Kudos
haitao
Novice
614 Views
I'll try.
This forum is so good and the people are so nice.
Thanks.
hhtlib
0 Kudos
Reply