Question

I want to store each block of characters that are seperated by a space at a specified index in my array. Here is my code:

with Ada.Text_IO; use Ada.Text_IO;

procedure Test_Read is

    Input_File    : File_Type;
    type Arr_Type is array (Integer range <>) of Character;
    Arr :   Arr_Type (1 .. 3);

begin

   Ada.Text_IO.Open (File => Input_File, Mode => Ada.Text_IO.In_File, Name => "input.txt");

    while not End_OF_File (Input_File) loop
        Ada.Text_IO.Get (File => Input_File, Item => Arr(1));
        Ada.Text_IO.Put (Item => Arr(1));
    end loop;

 Ada.Text_IO.Close (File => Input_File); 

end Test_Read;

The file "input.txt" contains:

ABCD EFGH IJK

The ouput I get for Put(Arr(1)) is the full line:

ABCD EFGH IJK

The output I want for Put(Arr(1)) is:

ABCD
Was it helpful?

Solution

For a start, your data type does not match the problem.

The type Character contains a single (ISO-8859-1) character. Your problem description sounds like you want to be able to store each block as an unspecified number of characters. The type Ada.Strings.Unbounded.Unbounded_String is suited for that purpose.

with Ada.Strings.Unbounded;
...
   type Block_Of_Characters is new Ada.Strings.Unbounded.Unbounded_String;

Your problem description is not explicit about the number of blocks of characters you expect, but for now I will assume that you always expect exactly three blocks (as your example data and source text both indicate).

   type Block_Collection is array (Positive range <>) of Block_Of_Characters;
   Blocks : Block_Collection (1 .. 3);

Opening the data file looks fine.

The read loop should be a bit different:

   Buffer : Character;
begin
   Open (File => Input_File,
         Mode => In_File,
         Name => "input.txt");

   for Index in Blocks'Range loop
      Read_A_Single_Block :
      loop
         exit when Index = Blocks'Last and End_Of_File (Input_File);

         Get (File => Input_File,
              Item => Buffer);

         exit Read_A_Single_Block when Buffer = ' ';

         Append (Source   => Blocks (Index),
                 New_Item => Buffer);
      end loop Read_A_Single_Block;
   end loop;

OTHER TIPS

While it's been 22 years since I last programmed anything in Ada, it's clear that you're not checking for a space.
Start with an array index variable pointing to 1.
You need to check if the character you 'got' using Ada.Text_IO.Get is a space.
If it is a space, add one to the index and always use Arr(index).
This way you'd break the character stream into several arrays.
Also, be sure to check if your index gets out of bounds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top