Adapted Constraint_error: invalid input for "Value:

I am trying to use Integer'Value to convert a string to Integer. This works fine for the first loop through the file, but after that I get a bad input for the value (raised by Constraint_Error. I was hoping someone could show me the error of my ways so that I could convert the string to an integer for each loop.

WITH Ada.Text_IO, Ada.Integer_Text_IO; USE Ada.Text_IO, Ada.Integer_Text_IO; PROCEDURE Isbntest IS FUNCTION Strip(The_String: String; The_Characters: String) RETURN String IS Keep: ARRAY (Character) OF Boolean := (OTHERS => True); Result: String(The_String'RANGE); Last: Natural := Result'First-1; BEGIN FOR I IN The_Characters'Range LOOP Keep(The_Characters(I)) := False; END LOOP; FOR J IN The_String'RANGE LOOP IF Keep(The_String(J)) THEN Last := Last+1; Result(Last) := The_String(J); END IF; END LOOP; RETURN Result(Result'First .. Last); END Strip; Input: File_Type := Ada.Text_IO.Standard_Input; BEGIN WHILE NOT End_of_File(Input) LOOP DECLARE Line : String := Ada.Text_IO.Get_Line(Input); StrippedLine : String := line; ascii_val: Integer :=0; BEGIN StrippedLine := Strip(Line, "-"); ascii_val := integer'value(StrippedLine); Put(ascii_val); Put_line(StrippedLine); END; END LOOP; Close (Input); end isbntest; 
0
source share
1 answer

The problem is that you fiddled with the length of the array after creating it. Do not do that.

Instead

  DECLARE Line : String := Ada.Text_IO.Get_Line(Input); StrippedLine : String := line; BEGIN StrippedLine := Strip(Line, "-"); 

Just initialize Stripped_Line right to the size you want when you declare it.

  DECLARE Line : String := Ada.Text_IO.Get_Line(Input); StrippedLine : String := Strip(Line, "-"); BEGIN 

I assume your strip function is working correctly here.

+4
source

Source: https://habr.com/ru/post/1273597/


All Articles