如何检查输入是否为枚举类型
How to check if input is an enumeration type
我正在读取键盘输入。输入应该匹配枚举类型中定义的元素之一。这是枚举类型的示例:
type NameType is (Bob, Jamie, Steve);
如果我收到的输入不是这 3 个之一,Ada 会引发 IO 异常。我该如何处理这个问题,以便我可以简单地显示“重试”消息而不让程序停止?
您可以尝试进行未经检查的转换,将值放入 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;
创建 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
的实例 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;
替代方法包括:
我正在读取键盘输入。输入应该匹配枚举类型中定义的元素之一。这是枚举类型的示例:
type NameType is (Bob, Jamie, Steve);
如果我收到的输入不是这 3 个之一,Ada 会引发 IO 异常。我该如何处理这个问题,以便我可以简单地显示“重试”消息而不让程序停止?
您可以尝试进行未经检查的转换,将值放入 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;
创建 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
的实例 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;
替代方法包括: