Ada - getting string from text file and store in array

▼魔方 西西 提交于 2019-12-13 06:01:09

问题


Hi im just wondering how to put data in an array if i loop txt and store it in A_Composite Name.

procedure Main is
       type An_Array is array (Natural range <>) of A_Composite;
       type A_Composite is
          record
             Name  : Unbounded_String;
          end record;

       File       : Ada.Text_IO.File_Type;
       Line_Count : Integer := 0;


    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

             --I want to store Line String to array. but i don't know how to do it      

          end;
       end loop;
       Ada.Text_IO.Close (File);
end Main;

回答1:


Ok, you have an unconstrained array here. This has implications; you see an unconstrained array gains its definite length when the object (general sense, not OOP) is declared or initialized.

As an example, let's look at strings (which are unconstrained arrays of characters) for an example to see how this works:

-- Create a string of 10 asterisks; the initialization takes those bounds.
A : constant string(1..10):= (others => '*');

-- Create a string of 10 asterisks; but determined by the initialization value.
B : constant string := (1..10 => '*');

-- Another way of declaring a string of 10 asterisks.
C : constant string := ('*','*','*','*','*','*','*','*','*','*');

Now, you can get these bounds from a function call; this means that we can use function-calls to return these values recursively.

Function Get_Text return An_Array is
  Package Unbounded renames Ada.Strings.Unbounded;
  -- You'll actually want the Get_Line that takes a file.
  Function Get_Line return Unbounded.Unbounded_String
    renames Unbounded.Text_IO.Get_Line;
begin
  return (1 => (Name => Get_Line)) & Get_Text;
exception
  when End_Error => return ( 1..0 => (Name => Unbounded.Null_Unbounded_String) );
end Get_Text;

So, that's how you'd do it using an unconstrained array.



来源:https://stackoverflow.com/questions/31410589/ada-getting-string-from-text-file-and-store-in-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!