Number Parsing in Ada
Our number parsing program demonstrates how to parse numbers from strings in Ada. Here’s the full source code:
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:
This example demonstrates basic number parsing in Ada, including handling of different numeric types and error conditions.