Ada- raised Constraint_error : bad input for '

2019-08-27 17:05发布

问题:

I'm trying to use Integer'Value to convert a string to an Integer. This works fine for the first loop through a file, but after that I get a bad input for 'value (raised Constraint_Error. I was hoping someone could show me the error of my ways, so that I can convert the string to an integer on 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;

回答1:

The problem is that you're messing with the length of an array after you created it. Don't do that.

Instead of

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

Just initialise Stripped_Line directly to the correct size when you declare it.

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

I'm assuming your "Strip" function works correctly here..