Ada- raised Constraint_error : bad input for 'Value:

不想你离开。 提交于 2019-12-25 08:48:26

问题


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..



来源:https://stackoverflow.com/questions/46532176/ada-raised-constraint-error-bad-input-for-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!