将字符串输入与枚举类型进行比较

Compare a string input to an Enumerated type

我想比较字符串和枚举。我已经编写了我正在尝试的示例代码。由于 String 和 Enumerated 类型不同,我该如何在 Ada 中正确执行此操作?

WITH Ada.Text_IO; USE Ada.Text_IO;

PROCEDURE ColorTest IS

   TYPE StopLightColor IS (red, yellow, green);

   response : String (1 .. 10);
   N : Integer;

BEGIN
   Put("What color do you see on the stoplight? ");
   Get_Line (response, N);
   IF response IN StopLightColor THEN
      Put_Line ("The stoplight is " & response(1..n));
   END IF;

END ColorTest;

首先为StopLightColor实例化Enumeration_IO:

package Color_IO is new Ada.Text_IO.Enumeration_IO(StopLightColor);

那么您可以执行以下任一操作:

  • 使用 Color_IO.Get 读取值,捕获出现的任何 Data_Error,如 所示 Enumeration_IO 的类似实例。

  • 使用Color_IO.Put获得Stringresponse进行比较。

顺便说一句,Stoplight_Color 可能是枚举类型标识符的更一致的样式。

另一种可能性:

Get_Line (response, N);
declare
    Color : StopLightColor;
begin
    Color := StopLightColor'Value(response(1..N));
    -- if you get here, the string is a valid color
    Put_Line ("The stoplight is " & response(1..N));
exception
    when Constraint_Error =>
        -- if you get here, the string is not a valid color (also could
        -- be raised if N is out of range, which it won't be here)
        null;
end;

回答您的实际问题:

Ada 不允许您直接比较不同类型的值,但幸运的是,有一种方法可以将枚举类型转换为字符串,这总是可行的。

对于任何枚举类型 T 都存在一个函数:

function T'Image (Item : in T) return String;

其中 returns 传递给它的枚举对象的字符串表示形式。

使用它,您可以声明一个函数,该函数比较字符串和枚举类型:

function "=" (Left  : in String;
              Right : in Enumerated_Type) return Boolean is
begin
   return Left = Enumerated_Type'Image (Right);
end "=";

如果要进行不区分大小写的比较,可以在比较之前将两个字符串都映射为小写:

function "=" (Left  : in String;
              Right : in Enumerated_Type) return Boolean is
   use Ada.Characters.Handling;
begin
   return To_Lower (Left) = To_Lower (Enumerated_Type'Image (Right));
end "=";