comp.lang.ada
 help / color / mirror / Atom feed
From: Adam Beneschan <adam@irvine.com>
Subject: Re: Beginner Question
Date: Wed, 20 Oct 2010 15:45:23 -0700 (PDT)
Date: 2010-10-20T15:45:23-07:00	[thread overview]
Message-ID: <b52542a1-bc69-4ce5-8450-b450a4adaaf1@p37g2000pra.googlegroups.com> (raw)
In-Reply-To: 90ceb514-83aa-44c2-b253-218956d8426d@d17g2000yqm.googlegroups.com

On Oct 20, 2:41 pm, SpoonThief <spoonth...@gmail.com> wrote:
> So, I have a question that may seem painfully obvious, but how does
> one go about parsing a Float from a string that has other data in it
> too? I'm getting a line from the keyboard that has a float and a
> custom type in it, and I need to separate the two values. I'm using a
> call to Get_Line to get the entire line the user entered as a string,
> and when I try to call Float'Value (In_String (1 .. Last)), I get a
> constraint error. Is there any way to parse a float and a custom
> subtype (Excellent, Good, Fair, Poor) from one string, or am I going
> about this the entirely wrong way? Any help would be much appreciated,
> and if clarification is needed because I wasn't clear, just ask. Thank
> you in advance!

Float'Value expects the entire string to look like a float.

The Float_IO generic in Ada.Text_IO has a Get routine that will let
you parse a float off the beginning of the string.  (If you're using
the predefined Float type, Ada.Float_Text_IO is a ready-made
instantiation of Float_IO.)  Similarly, there's an Enumeration_IO
generic in Ada.Text_IO that will let you parse your custom enumeration
type.  Both routines return a Last parameter that gives you the index
of the last character it used.  So something like this should work, if
T is your enumeration type:

   The_Float : Float;
   The_T : T;
   F_Last : Positive;
   T_Last : Positive;

   package T_IO is new Ada.Text_IO.Enumeration_IO (T);

   Ada.Float_Text_IO.Get (In_String (1 .. Last), The_Float, F_Last);
   T_IO.Get (In_String (F_Last + 1 .. Last), The_T, T_Last);

More info is in RM sections A.10.9 and A.10.10.

Those are simple ways to get things to work.  If you need more control
over the parsing, check out the operations in Ada.Strings.Fixed (RM A.
4.3); you could use those to search for blanks or whatever other
character you need to, and then once you figure out the beginning and
ending indexes of the floating-point part of the input, say, then you
can use Float'Value (In_String (Begin_Index .. End_Index)).

                             -- Adam



  parent reply	other threads:[~2010-10-20 22:45 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2010-10-20 21:41 Beginner Question SpoonThief
2010-10-20 22:43 ` Jeffrey Carter
2010-10-20 22:45 ` Adam Beneschan [this message]
2010-10-21  7:28 ` Dmitry A. Kazakov
replies disabled

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