Previous topic | Ada Home Page | Index

Safe Input of Enumerated Types

Using GET with enumerated types can cause an error, if an invalid value is entered. ADA lets you catch those errors, by providing an exception handler for the error.

The example here shows how you can read a value representing a day of the week from the user and be guaranteed that something appropriate is typed. If something invalid is entered, the procedure reports the error and gives the user another chance.



   type week_days is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun );
   subtype work_days is week_days range Mon .. Fri;
   subtype weekend_days is week_days range Sat .. Sun;


procedure safe_get_day (out_day : out week_days;
                 min : in week_days := week_days'FIRST;
                 max : in week_days := week_days'LAST ) is

-- procedure for the safe input of enumeration values

   local_day : week_days;        -- local input var
   good_day : BOOLEAN := FALSE;  -- loop control

begin -- safe_get_day
   while not good_day loop
   begin -- while block
      PUT("Enter an day between ");
      PUT( min ); PUT(" and "); PUT( max ); PUT(" ");
      GET( local_day );
      -- this point is reached only when input is a day code
      if (local_day < min) or else (local_day > max) then
         raise DATA_ERROR;
      else
         good_day := TRUE;
      end if;

      -- this point is reached if input is a valid day code
      -- between min and max

     exception
      when DATA_ERROR =>
         PUT_LINE("Invalid day!. Good days are ");
         for this_day in week_days range min .. max loop
             PUT( this_day ); PUT(" ");
         end loop;
         NEW_LINE; SKIP_LINE; -- tidy up terminal
     end;   -- protected while block
   end loop;
   -- this point can only be reached when valid value input
   SKIP_LINE;               -- tidy up terminal handling
   out_day := local_day;    -- export input value
end safe_get_day;


Previous topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 21 Feb 96