Re: reading a text file and printing (using Delphi)


[ DelphiLand Discussion Forum ]

Posted by webmaster Guido on April 28, 2003 at 18:09:00:

In Reply to: reading a text file and printing (using Delphi) posted by Jason on April 28, 2003 at 07:53:00:

: How do I write a Delphi program that reads a text file of Integers and then prints to screen the largest and smallest values found in the file. The file is called Input.txt.

: These numbers are similar to the ones I am going to use

: 12
: 14
: 2
: 78
: 3

: I want it say:
: The largest number found in the file input.txt is 78.
: The smallest number found in the file input.txt is 2.

: How do I do this?

---------------

For the following code, we assume that there is a textfile c:\test\input.txt with a text that represents one valid integer on each line.

The textfile is read into a listbox component, so you can check the results. If you don't want this, simply hide the listbox, or otherwise read the textfile into an invisible object such as a StringList.

To keep it simple, there is no error checking. Delphi will show an error message under certain conditions, for example if the file is not found, or if it's empty, or if there is a line that does not represent a valid integer. Of course, in a real application, you'd have to add some error checking. As usual, this is more complicated than the actual task of finding the largest / smallest number :)

procedure TForm1.Button2Click(Sender: TObject);
var
  FileName: string;
  i, Number, Largest, Smallest: integer;
begin
  FileName := 'c:\test\input.txt';
  ListBox1.Items.LoadFromFile(FileName);
  // Set first number of list in Largest and Smallest 
  Number := StrToInt(ListBox1.Items[0]);
  Largest := Number;
  Smallest := Number;
  // Compare all next numbers with Largest and Smallest.
  // If a number is larger than Largest, put number in Largest.
  // If a number is smaller than Smallest, put number in Smallest.
  for i := 1 to ListBox1.Items.Count - 1 do begin
    Number := StrToInt(ListBox1.Items[i]);
    if Number < Smallest then Smallest := Number
    else if Number > Largest then Largest := Number;
  end;
  Label1.Caption := 'Largest number found in file ' +
    FileName + ' : ' + IntToStr(Largest);
  Label2.Caption := 'Smallest number found in file ' +
    FileName + ' : ' + IntToStr(Smallest);
end;



Related Articles and Replies:


[ DelphiLand Discussion Forum ]