【问题标题】:Implementation of Integer'Value("X") in AdaInteger'Value("X") 在 Ada 中的实现
【发布时间】:2021-11-13 12:53:36
【问题描述】:

我将创建一个带有两个参数的子程序;一个字符串和一个整数。子程序将比较这两者,看看它们是否相同。

例如:

键入一个正好包含 5 个字符的字符串和一个整数:12345 123

-- 用户类型以粗体显示

他们不一样!

with Ada.Text_IO;         use Ada.Text_IO;                                                                
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; 
 
procedure Test2 is
    
    function String_Integer_Check(
        S : in String;
        I  : in Integer) return Boolean is         
    begin
        if Integer'Value(S) = I then
            return True;       
        else 
            return False;
        end if;  
    end String_Integer_Check;
           
    S : String(1..5);
    I : Integer;
   
begin
    Put("Type in a string containing exactly 5 characters, and an integer: ");
    Get(S);
    Get(I);
    Put("They are ");
   
    if String_Integer_Check(S, I) = False then
        Put("not ");
    end if;
   
    Put("the same.");  
end Test2;

我的程序可以工作,假设用户输入了一个 5 个字符的字符串。如果用户不这样做,我的程序将无法运行。我该如何解决这个问题?

如果我输入 123 1234(字符串是 3 个字符,整数是 4 个数字),我会得到这个错误:

他们是

引发 CONTRAINT_ERROR : 'Value: "123 1" 的错误输入

【问题讨论】:

  • 为什么要将字符串与整数进行比较?它们是不同的类型。字符“1”与整数 1 的值不同。您是否尝试将这两个值读取为整数?如果这样做,您将不会有输入问题,并且比较两个值非常简单。
  • 任务是比较一个字符串和一个整数,看看它们是否相同。通过使用 Integer’Value(S),您可以将字符串转换为整数。问题仍然存在,如果一个字符串小于 5 怎么办
  • 他们确实按您的要求输入了一个正好为 5 个字符的字符串:123 1,然后是另一个字符串 234。使用. 来表示空格,如果他们输入123..123,您会期望发生什么?或.123.123他们期望发生什么?此外,您只需要求他们输入正好 5 个字符的字符串; !@£$% 呢?或许您应该指定 5 个数字。并且可能在调用Integer’Value 之前检查输入是否符合您的规范。
  • 你的函数应该只返回Integer'Value (S) = I,你的测试应该是if not String_Integer_Check (S, I) then

标签: string ada


【解决方案1】:

确保两个输入位于不同的行上。您看到的 I/O 问题是由于在同一输入行上混合了字符串 I/O 和整数 I/O。当输入的字符串部分包含多于或少于 5 个字符时,这是一个问题。

with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure value_compare is
   str_num : String (1 .. 80);
   length  : Natural;
   num     : Integer;
begin
   Put ("Enter a 5 digit number: ");
   Get_Line (Item => str_num, Last => length);
   if length = 5 then
      Put ("Enter a number: ");
      Get (num);
      if num = Integer'Value (str_num(1..Length)) then
         Put_Line ("The two values are equal.");
      else
         Put_Line ("The two values are not equal.");
      end if;
   else
      Put_Line
        ("The input value " & str_num (1 .. length) &
         " does not contain 5 exactly characters.");
   end if;
end value_compare;

【讨论】:

  • 这可以进一步解释为什么/如何这回答了 OP 的问题。
猜你喜欢
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-03-13
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多