• Welcome to Powerbasic Museum 2020-B.
 

News:

Forum in repository mode. No new members allowed.

Main Menu

How to read a text file into a string array

Started by Chris Chancellor, January 11, 2019, 03:07:53 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Chris Chancellor

Hello Charles

i have the  text file below which i need to read into a string array   ArStr[ ] 

how do i write the program to read this file with each line entry is demakated by a carriage return ?


lin1                                   
lin2 rwerwe5rt34                       
lin3  mnner erert                       
lin4  jldjl g                           
lin5  fhrtu 5 56543                     
lin6   jre4t 34@45                     
This is Line 7                                 
O2 in Line 8                                       
lin9   rtyrek trtr                     
lin10                     



so that string array elements are
  ArStr[1]  = "lin1"
  ArStr[1]  = "lin2 rwerwe5rt34"

and so on

Charles Pegge

Hi Chris,

This is a slightly modified version of examples\DataProcessing\LineSplitter1.o2bas



'=============
'LINE SPLITTER
'=============

indexbase 1
string lines[100000] 'static lines array
string cr             '
int b,i,j            '


'data:
'=====

'txt=getfile "s.txt"

'txt=nuls 100000
'sendMessage richedit1,WM_GETTEXT,100000, strptr txt
'
string txt="11
22
33
44
55
66

77"

'initial
'=======
'
'
b=1  'start of line
i=0  'lines array index
j=1  'char index
'
'
'splitter loop
'=============
'
do
  select asc(txt,j)
  case 0
    if j-b>0 then
      i++
      lines[i]=mid(txt,b,j-b) 'FINAL LINE
    end if
    exit do
  case 10 'LF TERMINATED LINES
    i++
    lines[i]=mid(txt,b,j-b)
    b=j+1
  case 13 'CR AND CRLF TERMINATED LINES
    i++
    lines[i]=mid(txt,b,j-b)
    if asc(txt,j+1)=10 then j++ 'SKIP LF
    b=j+1
  end select
  j++   
end do


cr=chr(13)+chr(10)
print "Lines:  " i cr +
      "Line 5: " lines[5] + cr +
      "Last:   " lines[i]

Chris Chancellor

Thanxx a lot , Charles

This is exactly what i wanted,  thanxx for your invaluable time,  you really made O2 a great language