Вот и ты; Я также сделал так, чтобы вы могли добавлять отрицательные числа.
(Если это не то, что вы хотите, измените тип элемента Vector на Natural
или Positive
по желанию.)
Обратите внимание, что --'
комментарии - обходной путь к ошибочному выделителю синтаксиса.
Pragma Ada_2012;
Pragma Assertion_Policy( Ignore );
Pragma Restrictions( No_Implementation_Aspect_Specifications );
Pragma Restrictions( No_Implementation_Pragmas );
With
Ada.Strings.Equal_Case_Insensitive,
Ada.Text_IO.Text_Streams;
Procedure Example is
-- Counting and indexing types.
Type Count is range 0..100;
Subtype Index is Count range Count'Succ(Count'First)..Count'Last; --'
-- Array-type; its range is constrained by Index.
Type Vector is Array(Index range <>) of Integer;
-- Here we build the input-vector.
Function Get_Input return Vector is
-- Here we get user-input; we pass our working-set as a parameter so
-- that it can be built in-place; this also ensures that we only ever
-- generate a result of the appropriate length.
Function Get_Working( Working : Vector:= (2..1 => <>) ) return Vector is
Function "="(Left, Right : String) Return Boolean
renames Ada.Strings.Equal_Case_Insensitive;
Begin
-- We never try to add to a full array.
if Working'Length = Index'Last then
return Working;
end if;
-- We get an integer, or are finished.
loop
Ada.Text_IO.Put( "Enter an integer or type 'Done': " );
READ_INPUT:
Declare
User_Input : Constant String:= Ada.Text_IO.Get_Line;
Begin
return Get_Working( Working & Integer'Value(User_Input) ); --'
Exception
when Constraint_Error =>
if User_Input = "Done" then
return Working;
end if;
End READ_INPUT;
end loop;
End Get_Working;
Begin
Return Get_Working;
End Get_Input;
Procedure Print( Object : Vector ) is
Begin
Ada.Text_IO.Put( '[' );
for Index in Object'Range loop --'
Ada.Text_IO.Put( Integer'Image(Object(Index)) ); --'
if Index /= Object'Last then --'
Ada.Text_IO.Put(',');
end if;
end loop;
Ada.Text_IO.Put( ']' );
End Print;
Begin
declare
V : constant Vector:= Get_Input;
begin
Print( V );
Ada.Text_IO.New_Line( 2 );
end;
Ada.Text_IO.Put_Line( "Done." );
End Example;
Пример выполнения:
Enter an integer or type 'Done': 21
Enter an integer or type 'Done': 4
Enter an integer or type 'Done': 18
Enter an integer or type 'Done': DONE
[ 21, 4, 18]
Done.