Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Pretty much all the standard ways to parse a string into a scalar value of some kind in Ada will produce an exception of some kind when/if an invalid string is read. There isn't anything wrong with that. Just handle the exception.</p> <p>Even if you wrote your own string parsing to integer routines, you'd have to somehow handle the situation where the user entered an invalid string. Right?</p> <p>I guess the only "technique" involved is that you can put exception handlers on subroutines, or even on <code>declare ... begin ... end</code> blocks that you put inline in your code. This way only the code within the block is aborted. Generally I prefer to see subroutines used. So you'd get something like:</p> <pre class="lang-ada prettyprint-override"><code>function User_Integer return Integer is begin loop begin ada.integer_text_io.get(integer_variable); return integer_variable; exception when ADA.IO_EXCEPTIONS.DATA_ERROR =&gt; Ada.Text_IO.Put_Line ("Try a number from 1 to 3, Sherlock"); Print_Menu; end; end loop; end User_Integer; </code></pre> <p>Now, this being the case, for quick-and-dirty Ada menus I generally don't do numeric menus like above. Instead, make an enumerated type. That way you can print the menu options using a <code>'image</code> in a loop through the menu type, and Ada will handle the text parsing when you use <code>'value</code> or <code>Ada.Text_IO.Enumeration_IO</code>.</p> <pre class="lang-ada prettyprint-override"><code>type Menu_Selection_Option is (Eat, Drink, Sleep); package Menu_IO is new Ada.Text_IO.Enumeration_IO (Menu_Selection_Option); function User_Selection return Integer is begin loop declare Selection : Menu_Selection_Option; begin Menu_IO.Get(Selection); return Selection; exception when ADA.IO_EXCEPTIONS.DATA_ERROR =&gt; Ada.Text_IO.Put_Line ("Unrecognized option. Try again Sherlock"); Print_Menu; end; end loop; end User_Selection; </code></pre> <p>The nice thing about this is that you don't have to change your menu-printing code or your parsing code when the list of menu options changes.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload