I just picked up Ada a few minutes ago, so forgive me if this seems like a trivial question.
There is a loop in my program that causes an end error if the input ends with a " " character. My program works for correct input but I'm trying to catch some edge cases.
> echo "1 2 3 " | ./eofloop3a
raised ADA.IO_EXCEPTIONS.END_ERROR : a-textio.adb:506
The loop in question
procedure fun1 is
F : Integer;
begin
while (not End_Of_File) loop
Get(F);
end loop;
end fun1;
Why is this happening and is there a way to prevent reading out of bounds? I was thinking the while condition should've prevented this from happening.
This is the expected result. It happens because "The exception End_Error
is propagated by a Get
procedure if an attempt is made to skip a file terminator." In the context of your example input, after Get
has read 3
, End_Of_File
remains False
. Get
then "skips any leading blanks" and encounters the end of file while attempting to read "the longest possible sequence of characters matching the syntax of a numeric literal."
One solution is to catch the exception and handle it as warranted by your use case. For example,
procedure Fun1 is
F : Integer;
begin
while (not End_Of_File) loop
Get (F);
end loop;
exception
when End_Error =>
Put_Line ("Warning: Ignoring trailing non-numeric data.");
end Fun1;
Also consider catching Data_Error
if your program is intended to reject malformed integer literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With