Ada: How to check if input is an enumeration type [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-24 01:39:17

问题


I am reading input from the keyboard. The input is supposed to match one of the elements defined in an enumeration type. Here is an example of the enum type:

type NameType is (Bob, Jamie, Steve);

If I receive an input that is not one of these 3, ada raises an IO exception. How do I handle this to where I can simply display a "try again" message and not have the program stop? THANKS


回答1:


Create an instance of Enumeration_IO for Name_Type, say Name_IO. In a loop, enter a nested block to handle any Data_Error that arises. When Name_IO.Get succeeds, exit the 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;



回答2:


You might try an unchecked conversion to get the value into a variable of NameType then call 'valid on that variable.

Edit to include the example from 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;


来源:https://stackoverflow.com/questions/43151902/ada-how-to-check-if-input-is-an-enumeration-type

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