I have the following code to check if a string entered is alphanumeric or not in Ada:
function Check_AplhaNumeric(input_String:in String) return Boolean is
begin
Alphanumeric_or_not:=TRUE;
for Index_Character in 1..Length(To_Unbounded_String(input_String)) loop
Alphanumeric_or_not:=Is_Alphanumeric(Character'Val(Character'Pos(input_String(Index_Character))));
exit when Alphanumeric_or_not = False;
end loop;
return True;
end Check_AplhaNumeric;
The following code calls the above function thrice
Is_it:=Check_AplhaNumeric(stringInput(1..First_Semicolon-1));
Is_it:=Check_AplhaNumeric(stringInput(First_Semicolon+1..Second_Semicolon-1));
Is_it:=Check_AplhaNumeric(stringInput(Second_Semicolon+1..stringInput'Last));
I have an input string eg: a;value;b
which is separated into three parts based on the semicolon in the input. The first call to Check_AlphaNumeric
works just fine and detects if the string is alpha numeric or not, However, the calls which include the second and third part from the string generate the following error:
raised CONSTRAINT_ERROR : alpha.adb:247 index check failed
I don't know what seems to be going wrong, since it works just fine when I call it the first time for the part before the first semicolon in the string.
Even if one of the characters is not alphanumeric, I need it to print some message and exit the program.
The body of your function inherits the range of the stringInput, which means you're looping over a range that is invalid.
Let's say stringInput contains the string "1337;h4x0r;foo"
The first time you call Check_Alphanumeric
, the range of input_String
is 1..4. You loop through 1..4, which is fine. The second time, the range is 6..10, but now you loop over the range 1..5, which is clearly not what you want.
Try instead to loop over the range of the input array:
for Index_Character in input_String'Range loop
And don't convert to unbounded_string just to get the length of a string/array, use the 'Length
attribute instead. Remember that all arrays have 'First
, 'Last
, 'Length
and 'Range
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.