Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i prevent this loop from reading if the input ends on a space?

Tags:

ada

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.

like image 698
Koala Avatar asked Mar 02 '23 02:03

Koala


1 Answers

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.

like image 160
trashgod Avatar answered Apr 28 '23 12:04

trashgod