如果输入以 space 结尾,我如何防止此循环读取?

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

几分钟前我刚接过 Ada,如果这看起来像是一个微不足道的问题,请原谅我。

如果输入以“ ”字符结尾,我的程序中有一个循环会导致结束错误。 我的程序适用于正确的输入,但我正在尝试捕捉一些边缘情况。

> echo "1 2 3 " | ./eofloop3a

raised ADA.IO_EXCEPTIONS.END_ERROR : a-textio.adb:506

有问题的循环

procedure fun1 is
   F : Integer;
begin
  while (not End_Of_File) loop
    Get(F);
  end loop;
end fun1;

为什么会发生这种情况,有没有办法防止读取越界?我在想 while 条件应该可以防止这种情况发生。

这是预期的结果。它 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 然后“跳过任何前导空格”并在尝试读取“与数字文字语法匹配的最长可能字符序列”时遇到文件末尾。

一种解决方案是捕获异常并根据您的用例进行处理。例如,

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;

如果您的程序旨在拒绝格式错误的整数文字,也请考虑捕获 Data_Error

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   Name : String := "data.txt";
   The_File : File_Type;

begin
   Open(File => The_File,
        Mode => In_File,
        Name => Name);
   
   while not End_Of_File(The_File) loop
      declare
         Str : String := Get_Line(The_File);
         Idx : Positive;
         F   : Integer;
      begin
         Idx := Str'First;
         while Idx <= Str'Last loop
            Get(From => Str(Idx..Str'Last),
                Item => F,
                Last => Idx);
            Put(F'Image);
            Idx := Idx + 1;
         end loop;
         New_Line;
      end;
   end loop;
   Close(The_File);
end Main;

没有产生异常。 一次一行地读取输入文件,然后从上述行读取生成的字符串中读取以处理每个整数。 即使输入行包含尾随字符,这也毫无例外地工作。