1

How can I read a word (skip whitespace and read characters until a whitespace is encountered) similar to scanf("%s") in C?

ArekBulski
  • 4,520
  • 4
  • 39
  • 61

3 Answers3

3

Reading a word from standard input. Written as a function. (Not tested.)

function Next_Word return String is
   package Latin_1 renames Ada.Characters.Latin_1;

   subtype Whitespace is Character
     with Static_Predicate => Whitespace in ' ' | Latin_1.HT;

   use all type Ada.Strings.Unbounded.Unbounded_String;

   Word : Ada.Strings.Unbounded.Unbounded_String;
   Next : Character;
begin
   Skip_Leading_Space:
   loop
      Ada.Text_IO.Get (Next);
      exit when not (Next in Whitespace);
   end loop Skip_Leading_Space;

   Read_Word:
   loop
      Word := Word & Next;
      Ada.Text_IO.Get (Next);
      exit when Next in Whitespace;
   end loop Read_Word;

   return To_String (Word);
end Next_Word;
Jacob Sparre Andersen
  • 6,733
  • 17
  • 22
2
Skip_Leading_Space:
loop
   Next := Ada.Text_IO.Get;
   exit when not Next in Whitespace;
end loop Skip_Leading_Space;

Read_Word:
loop
   Word := Word & Next;
   Next := Ada.Text_IO.Get;
   exit when Next in Whitespace;
end loop Read_Word;
Jacob Sparre Andersen
  • 6,733
  • 17
  • 22
2

You want to scan, so it's best to use what is offered in the Ada standard library for this purpose. One candidate is Ada.Strings.Fixed.Find_Token.

with Ada.Strings.Fixed, Ada.Strings.Maps.Constants, Ada.Text_IO;
use Ada.Text_IO, Ada.Strings;

procedure Read_Word is
    Text  : constant String    := Get_Line;
    First : Positive;
    Last  : Natural;
    White : Maps.Character_Set := Maps.To_Set (" ");
begin
    Fixed.Find_Token
      (Source => Text,
       Set    => White,
       Test   => outside,
       First  => First,
       Last   => Last);
    Put_Line ("word is: " & Text (First .. Last) & '.');
end Read_Word;
B98
  • 1,229
  • 12
  • 20