【问题标题】:Ada- raised Constraint_error : bad input for 'Value:Ada-raised Constraint_error : bad input for 'Value:
【发布时间】:2017-10-03 05:32:50
【问题描述】:

我正在尝试使用 Integer'Value 将字符串转换为整数。这对于通过文件的第一个循环很好,但在那之后我得到了一个错误的'value输入(引发了Constraint_Error。我希望有人能告诉我我的方式的错误,这样我就可以将字符串转换为整数每个循环。

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;

【问题讨论】:

  • 如果您尝试转换为整数的字符串包含非数字字符,您认为会发生什么?
  • @JimRogers 该程序的目标是获取 ISBN 号码并检查它们的有效性。其中一个参数是数字可以带有任意数量的破折号 (-),并且应该显示没有它们的数字。功能是删除破折号。我相信 integer'value 返回字符串的 ascii 值,所以如果它包含非数字字符,它会抛出整数值。
  • 由于自 2007 年以来的 ISBN 有 13 位数字,您可能应该使用 Long_Integer(或定义您自己的整数类型 range 0 .. 10**13 - 1
  • @SimonWright 我不认为 Long_Integer 保证有 13 位数字。一般来说,请不要鼓励人们不必要地使用预定义的数字类型。
  • Integer'Value 返回数字字符串的整数值。当数字字符串的值超出整数范围时,会引发 Contraint_Error。如果您只想查看不带破折号的数字,只需打印剥离的输入字符串。

标签: arrays string ada


【解决方案1】:

问题是您在创建数组后弄乱了数组的长度。不要那样做。

代替

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

在声明时直接将 Stripped_Line 初始化为正确的大小。

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

我假设您的“Strip”功能在这里正常工作..

【讨论】: