Im having a trouble storing unbounded string to an array if I'mm getting it to .txt file. Here is my hardcoded data:
Data : An_Array := (1 => (Name => +"9 - Joe"),
2 => (Name => +"8 - Trisha "),
3 => (Name => +"7 - RR "),
4 => (Name => +"6 - Jane "),
5 => (Name => +"5 - Doe "));
What if I want to get the data from a .txt
file?
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Generic_Array_Sort;
procedure Main is
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
type A_Composite is
record
Name : Unbounded_String;
end record;
function "<" (L, R : A_Composite) return Boolean is
begin
return L.Name < R.Name;
end "<";
procedure Put_Line (C : A_Composite) is
begin
Put_Line (To_String (C.Name));
end Put_Line;
type An_Array is array (Natural range <>) of A_Composite;
procedure Sort is new Ada.Containers.Generic_Array_Sort (Natural, A_Composite, An_Array);
Data : An_Array := (1 => (Name => +"9 - Joe"),
2 => (Name => +"8 - Trisha "),
3 => (Name => +"7 - RR "),
4 => (Name => +"6 - Jane "),
5 => (Name => +"5 - Doe "));
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => "highscore.txt");
while not Ada.Text_IO.End_Of_File (File) loop
declare
Line :String := Ada.Text_IO.Get_Line (File);
begin
-- get data from .txt and I want it to sotre to Data : An_Array
end;
end loop;
Ada.Text_IO.Close (File);
Sort (Data);
for I in Data'Range loop
Put_Line (Data (I));
end loop;
end Main;
In Ada, any particular array has a fixed length; your
Data
has a length of 5, even though your typeAn_Array
can be used to declare arrays with any length you like (within reason! your computer only has a fixed amount of memory).I’m guessing that you want to deal with files where you don’t know beforehand how many lines there are.
You could do this by declaring
and keeping a count of how many entries you’ve used:
and when the loop ends
Data (1 .. Last)
contains your data (Data (Last + 1 .. 1000)
contains empty strings).But what if there are 1001 entries in your file?
You could try
Ada.Containers.Vectors
(ARM A.18.2) andAda.Containers.Generic_Sort
(ARM 18.29(9.1)) - you’d have to work out how to specifyBefore
, and to write your ownSwap
procedure.Inserting an
Unbounded_String
in an array ofUnbounded_String
s is trivial:But is that your actual problem?