Compare a string input to an Enumerated type

前端 未结 3 1099
北恋
北恋 2021-01-07 12:18

I am looking to do a comparison of a string to and enumeration. I have written a sample code of what I am attempting. Since a String and and Enumerated type are different, h

相关标签:
3条回答
  • 2021-01-07 12:56

    Another possibility:

    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;
    
    0 讨论(0)
  • 2021-01-07 13:04

    Answering your actual question:

    Ada doesn't allow you to compare values of different types directly, but luckily there is a way to convert an enumerated type to a string, which always works.

    For any enumerated type T there exists a function:

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

    which returns a string representation of the enumerated object passed to it.

    Using that, you can declare a function, which compares a string and an enumerated type:

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

    If you want to do a case-insensitive comparison, you could map both strings to lower case before comparing them:

    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 "=";
    
    0 讨论(0)
  • 2021-01-07 13:07

    First instantiate Enumeration_IO for StopLightColor:

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

    Then you can do either of the following:

    • Use Color_IO.Get to read the value, catching any Data_Error that arises, as shown here for a similar instance of Enumeration_IO.

    • Use Color_IO.Put to obtain a String for comparison to response.

    As an aside, Stoplight_Color might be a more consistent style for the enumerated type's identifier.

    0 讨论(0)
提交回复
热议问题