comp.lang.ada
 help / color / mirror / Atom feed
From: "Dmitry A. Kazakov" <mailbox@dmitry-kazakov.de>
Subject: Re: Newbie Question: Integer_IO an Data_error
Date: Fri, 27 Mar 2009 09:54:29 +0100
Date: 2009-03-27T09:54:29+01:00	[thread overview]
Message-ID: <rqz7n0iu5pyq.kua9eexb5wik.dlg@40tude.net> (raw)
In-Reply-To: 873ad0ueva.fsf@babel.localdomain

On Thu, 26 Mar 2009 14:57:13 -0700, Zachary Kline wrote:

> I wrote for my own amusement a simple number-guessing game, which
> works mostly as I intended.  The problem comes when handling
> exceptions.  I can handle the case where a user typed a number too large
> or too small: that's a Constraint_Error, and I just prompt again and
> read another guess.  The problem comes with Data_errors: if I try to
> handle that case the same way, we get a seemingly infinite loop.

A general advise is that when you read user input do not parse it as you
read. That cannot work.

Instead of that, read the whole line and then parse the string obtained,
using Ada.Text_IO.Integer_IO (or something better):

   type Guess is new Integer;
   package Guess_IO is new Ada.Text_IO.Integer_IO (Guess);

   use Guess_IO;
   function Get_Guess return Guess is
      Result : Guess;
   begin
      loop
         Put ("Your guess:");
         declare
            Line : constant String := Get_Line;
            Last : Positive;
         begin
            Get (Line, Result, Last);
            if Last = Line'Last then
               return Result;
            end if;
            Put_Line ("Unrecognized text after the number");
         exception
            when Constraint_Error =>
               Put_Line ("Out of range");
            when Data_Error =>
               Put_Line ("Not a number");
            when End_Error =>
               Put_Line ("Nothing found");
         end;
      end loop;
   end Get_Guess;

-- 
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de



      parent reply	other threads:[~2009-03-27  8:54 UTC|newest]

Thread overview: 9+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2009-03-26 21:57 Newbie Question: Integer_IO an Data_error Zachary Kline
2009-03-26 22:18 ` Tim Rowe
2009-03-26 23:57   ` Zachary Kline
2009-03-27  0:23     ` Tim Rowe
2009-03-27  0:03   ` Adam Beneschan
2009-03-27  0:19     ` Zachary Kline
2009-03-27  8:59   ` Jean-Pierre Rosen
2009-03-27  5:15 ` anon
2009-03-27  8:54 ` Dmitry A. Kazakov [this message]
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox