Ada:如何检查输入是否是枚举类型

时间:2017-04-01 01:45:47

标签: enumeration ada

我正在从键盘上读取输入。输入应该与枚举类型中定义的元素之一匹配。以下是枚举类型的示例:

type NameType is (Bob, Jamie, Steve);

如果我收到的输入不是这3个中的一个,则ada会引发IO异常。我如何处理这个问题,我可以简单地显示一个"再试一次"消息,没有程序停止?致谢

2 个答案:

答案 0 :(得分:4)

Name_Type创建Enumeration_IO的实例,例如Name_IO。在loop中,输入嵌套block以处理出现的任何Data_ErrorName_IO.Get成功后,exit loop

with Ada.IO_Exceptions;
with Ada.Text_IO;

procedure Ask is

type Name_Type is (Bob, Jamie, Steve);
package Name_IO is new Ada.Text_IO.Enumeration_IO (Name_Type);

begin
   loop
      declare
         Name : Name_Type;
      begin
         Ada.Text_IO.Put("Enter a name: ");
         Name_IO.Get(Name);
         exit;
      exception
         when Ada.IO_Exceptions.Data_Error =>
            Ada.Text_IO.Put_Line("Unrecognized name; try again.");
      end;
   end loop;
end Ask;

答案 1 :(得分:-2)

您可以尝试进行未经检查的转换,将值转换为NameType变量,然后调用'对该变量有效。

修改以包含ADAIC

中的示例
with Ada.Unchecked_Conversion;
with Ada.Text_IO;
with Ada.Integer_Text_IO;

procedure Test is

   type Color is (Red, Yellow, Blue);
   for Color'Size use Integer'Size;

   function Integer_To_Color is
      new Ada.Unchecked_Conversion (Source => Integer,
                                    Target => Color);

   Possible_Color : Color;
   Number         : Integer;

begin  -- Test

   Ada.Integer_Text_IO.Get (Number);
   Possible_Color := Integer_To_Color (Number);

   if Possible_Color'Valid then
      Ada.Text_IO.Put_Line(Color'Image(Possible_Color));
   else
      Ada.Text_IO.Put_Line("Number does not correspond to a color.");
   end if;

end Test;