We help IT Professionals succeed at work.

Little problem with TextFile reading

MarceloAlvim
MarceloAlvim asked
on
Hey, people.
Well, that must be pretty easy for most of you:
I am writing a program in which I have to read a text file. The problem is the text file has a line with integer numbers separated by commas (and spaces, of course).
At a certain point I want to read those numbers from the file and store them in variables, but I don't know how to handle the commas. If they were separated only by spaces (no matter how many), I think just using the read procedure as many times as necessary would do just fine, but since there are also commas between the numbers, I just can't figure out how to read them. Would you help me?
(well, I think that should be easy, but I'll probably raise the points if it's not)
Thanx,
Alvim.
Comment
Watch Question

Commented:
var

  F: TextFile;
  S: string;
begin
  if OpenDialog1.Execute then            { Display Open dialog box }
  begin
    AssignFile(F, OpenDialog1.FileName); { File selected in dialog }
    Reset(F);
    Readln(F, S);                        { Read first line of file }
    Edit1.Text := S;                     { Put string in a TEdit control }
    CloseFile(F);
  end;
end;
//here you just manipulate the s string
Mohammed NasmanSoftware Developer
CERTIFIED EXPERT

Commented:
Hello

 this code will remove the comma from string and convert it to spaces, is that what u need?

procedure TForm1.Button1Click(Sender: TObject);
var
  OldStr : String;
  NewStr : String;
begin
  OldStr := '18, 5, 7, 99';
  NewStr := StringReplace(OldStr,', ',' ', [rfReplaceAll]);
  ShowMessage(NewStr);
end;

Commented:
After reading an integer using Read(), just read a char using Read(). This should read in the comma and thus allow you to read the next integer afterwards.

A better solution would be to read a line into a string (ReadLn) and to process it afterwards yourself:

var
     S: string; //holds your comma-delimited numbers
     Dest: array[0..100] of Integer;
     Column: Integer; //"column" of integers you're currently at
     I,Number: Integer; //counter and temp. number
     Numeric: Boolean; //flag to recognize new columns

[...]
     // I assume that S holds a line with several numbers    
     Number:=0;
     Column:=0;
     Numeric:=False;
     for I:=1 to Length(S) do begin
          if S[I] in ['0'..'9'] then begin
               Numeric:=True; //set flag: we have a number
               Number:=Number*10+(Ord(S[I])-Ord('0')); //process next digit
          end else if Numeric then begin
               Dest[Column]:=Number; // Store the number
               Inc(Column);
               Numeric:=False;
          end;
     end;
     if Numeric then
          Dest[Column]:=Number; // Store the last number if any
[...]

Commented:
Oops, just saw a small glitch... this should be better:

var
     S: string; // holds your comma-delimited numbers
     Dest: array[0..100] of Integer; // array where we store the numbers
     Column: Integer; // "column" of integers you're currently at
     I,Number: Integer; // counter and temp. number
     Numeric: Boolean; // flag to recognize new columns

[...]
     // I assume that S holds a line with several numbers    
     Number:=0;
     Column:=0;
     Numeric:=False;
     for I:=1 to Length(S) do begin
          if S[I] in ['0'..'9'] then begin
               Numeric:=True; // set flag: we have a number
               Number:=Number*10+(Ord(S[I])-Ord('0')); // process this digit
          end else if Numeric then begin
               Dest[Column]:=Number; // store the number
               Inc(Column);
               Numeric:=False; // reset flag...
               Number:=0; //...and number
          end;
     end;
     if Numeric then begin
          Dest[Column]:=Number; // store the last number if any
          Inc(Column);
     end;
     // column now holds the count of numbers stored in Dest
[...]
Commented:
const
  NamePos = 0;
  AgePos = 1;
  WagesPos = 2;
var
  S: string;
  Afile: TextFile;
  Values: TStringList;
begin
  AssignFile(Afile, 'c:\myfile.txt');
  Reset(AFile);
  Values := TStringList.Create;
  try
    while not Eof(AFile) do
    try  
      Readln(Afile, S); //Get the next line
      Values.CommaText := S;  //Split the comma values
      Something := Values[NamePos];
      SomeAge := StrToInt(Values[AgePos]);
      SomeWage := StrToFloat(Values[WagesPos]);
    except
      //Handle conversion errors here
      //StrToInt errors etc
    end;
  finally
    Values.Free;
    CloseFile(Afile);
  end;
end;
This will place all the numbers into a string list, on number at a time:

var
  InFile: TextFile;
  List: TStringList;
  S: String;
begin
  AssignFile(InFile, 'C:\ee.txt');
  List := TStringList.Create;
  try
    try
      Reset(InFile);
      ReadLn(InFile, S);
      List.CommaText := S;
      {Do what ever with text}
    except
      on E: Exception do
        MessageDlg(E.Message, mtError, [mbOK], 0);
    end {try..except}
  finally
    List.Free;
    CloseFile(InFile);
  end; {try..finally}
end;

StringLists can accept comma delimited text using the CommaText property.

Hope this helps.

Stu.
Sorry cubud!  I didn't realise you posted a comment the same as mine :)  

Author

Commented:
Hey, Thank you all for the answers, I liked very much most of them. I'm accepting cubud's one, because I think it will be the best one for me right now.

Thanx, guys!!
See ya.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.