Question

I have an array that holds strings of a maximum of 20 characters:

subtype c_string is string(1..20);
type string_array is array (natural range 1..100) of c_string;

When I try to assign a string to a position of string_array, I get the following error if the string is not exactly 20 characters long:

raised CONSTRAINT_ERROR : (...) length check failed

This is the line of code that causes the problem:

str_a: string_array;
(....)
str_a(n) := "stringToAssign"        --Causes error

What would the best way to avoid this be?

Était-ce utile?

La solution

Your c_string can’t hold a maximum of 20 characters; it holds exactly 20 characters, hence the CE.

You could use Ada.Strings.Bounded if it’s important to have an upper limit, or Ada.Strings.Unbounded if you don’t actually care.

In the bounded case, that’d be something like

package B_Strings is new Ada.Strings.Bounded.Generic_Bounded_Length (Max => 20);
type String_Array is array (1 .. 200) of B_Strings.Bounded_String;

and then

Str_A : String_Array;
Str_A (N) := B_Strings.To_Bounded_String (“stringToAssign”);

There’s more in the Ada Wikibook.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top