On 03.08.14 23:42,
ag...@drrob1.com wrote:
> Procedure trimtest is
> Subtype String255FixedType is String(1..255);
>
> str : String255Fixedtype;
> STRLEN : Natural;
>
> BEGIN
> Put(" Enter line: ");
> Get_Line(Str,StrLen);
> Str := TRIM(Str,Side => Both);
> -- Str := Ada.Strings.Fixed.TRIM(str,side => Ada.Strings.both);
> Put_Line(" Line is: " & Str(1..StrLen) & " with length of " &
> Natural'image(StrLen) );
> End trimtest;
>
> This simple procedure compiles, but does give me an exception at
> run-time after I call trim. I don't understand how to avoid this. I
> am used to more flexible strings that are null terminated.
These are Ada.Strings.Bounded and Ada.Strings.Unbounded. Or,
if you want the greatest possible flexibility, wrap a pointer
to String in a type derived from Finalization.Controlled. This,
however, will likely turn into reinventing either of the former
language defined packages.
An object of type String255FixedType will always be what it is
by declaration: an array of exactly 255 components, indexed
by values between 1 and 255, inclusively. So, "fixed" is a
well chosen part of the subtype's name.
> How do I avoid a constraint_error exception at run-time?
One more way is to declare the string object where you need it
Get_Line (Str, StrLen);
declare
Trimmed : String := Trim (Str(1 .. StrLen), Side => Both);
begin
... do something with Trimmed
end;
Or pass the trimmed result to some procedure that works on it:
procedure Taking_Trimmed (S : String) is
-- S is of any length, and of any indexing subtype
begin
-- note: S'Length, S'First, etc are known here
end Taking_Trimmed;
...
Get_Line (Str, StrLen);
Taking_Trimmed (Trim (Str(1 .. StrLen), Side => Both));