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

ArekBulski
- 4,520
- 4
- 39
- 61
3 Answers
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
-
2Labels are there to make the code clearer and you obviously can make it a procedure using in, in/out and out parameters. You can also make it a function but depending on which Ada revision you use, you may not be able to use all type of parameter passing mode. – Frédéric Praca Apr 13 '17 at 07:18
-
1I'm too much of a teacher to give a full solution the first time around. ;-) – Jacob Sparre Andersen Apr 13 '17 at 08:31
-
2I would absolutely not drop the labels, as they make the source easier to read. – Jacob Sparre Andersen Apr 13 '17 at 08:32
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