Mr. Coffee Code
Mr. Coffee Code

Reputation: 65

How do I read each word and store it to a variable to use?

I'm new to Ada. Syntax is throws me off. I have 6 years in Java and it's similar to this what we do in java but I quite can't get it working. I'm studying using learn.adacore.com.

with Ada.Text_IO; Use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;

procedure TextFile is

   F      : File_Type;
   File_Name : constant String := "Store.txt";
begin
   
   Open (F, In_File, File_Name);
   
   while not End_Of_File (F) loop
      Put_Line (Get_Line (F));
   end loop;
   Close (F);
   
end TextFile;

This is my text file called Store.txt

Code    Department  Name/Vendor  Title          ID      Payrate
IL      Sales       John         Sales_person   1378    25.46

Upvotes: 2

Views: 205

Answers (1)

thindil
thindil

Reputation: 881

If you don't mind portability between different Ada compilers, you can use package GNAT.String_Split to split the whole line as array of separated String values:

with Ada.Text_IO;       use Ada.Text_IO;
with GNAT.String_Split; use GNAT.String_Split;

procedure TextFile is
   File   : File_Type;
   Tokens : Slice_Set;
begin
   Open (File, In_File, "Store.txt");
   -- Skip the file header
   Skip_Line (File);
   -- Read the data
   while not End_Of_File (File) loop
      -- Split the line from the file on array which contains separated
      -- words. Treat multiple spaces as a single separator (don't
      -- create empty elements).
      Create (Tokens, Get_Line (File), " ", Multiple);
      -- Print each of the array's values
      for I in 1 .. Slice_Count (Tokens) loop
         Put_Line (Slice (Tokens, I));
      end loop;
   end loop;
   Close (File);
end TextFile;

Upvotes: 3

Related Questions