Number Parsing in Ada
Our number parsing program demonstrates how to parse numbers from strings in Ada. Here’s the full source code:
with Ada.Text_IO;
with Ada.Float_Text_IO;
with Ada.Integer_Text_IO;
with Ada.Numerics.Long_Long_Elementary_Functions;
procedure Number_Parsing is
use Ada.Text_IO;
use Ada.Float_Text_IO;
use Ada.Integer_Text_IO;
use Ada.Numerics.Long_Long_Elementary_Functions;
F : Float;
I : Integer;
D : Integer;
U : Natural;
K : Integer;
begin
-- Parse a float
F := Float'Value("1.234");
Put(F, Fore => 1, Aft => 3, Exp => 0);
New_Line;
-- Parse an integer
I := Integer'Value("123");
Put(I, Width => 0);
New_Line;
-- Parse a hexadecimal number
D := Integer'Value("16#1c8#");
Put(D, Width => 0);
New_Line;
-- Parse an unsigned integer (Natural in Ada)
U := Natural'Value("789");
Put(U, Width => 0);
New_Line;
-- Parse a basic base-10 integer
K := Integer'Value("135");
Put(K, Width => 0);
New_Line;
-- Demonstrate error handling
begin
K := Integer'Value("wat");
exception
when Constraint_Error =>
Put_Line("Error: Invalid integer syntax");
end;
end Number_Parsing;
In Ada, we use the 'Value
attribute to parse strings into numbers. This attribute is available for all numeric types.
For floating-point numbers, we use Float'Value
. The precision is determined by the type we’re parsing into (Float
in this case).
For integers, we use Integer'Value
. Ada will automatically infer the base from the string representation. Hexadecimal numbers are represented with the base explicitly stated (e.g., 16#1c8#
).
Ada doesn’t have separate signed and unsigned integer types like some languages. Instead, we use Natural
for non-negative integers, which is a subtype of Integer
.
Ada doesn’t have a direct equivalent to the Atoi
function, but Integer'Value
serves the same purpose for parsing base-10 integers.
Error handling in Ada is done through exceptions. When parsing fails, a Constraint_Error
is raised, which we can catch and handle appropriately.
To run the program, save it as number_parsing.adb
and use your Ada compiler. For example, with GNAT:
$ gnatmake number_parsing.adb
$ ./number_parsing
1.234
123
456
789
135
Error: Invalid integer syntax
This example demonstrates basic number parsing in Ada, including handling of different numeric types and error conditions.