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

问题描述

几分钟前我刚刚接过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;

为什么会发生这种情况,并且有一种方法可以防止超出范围的读取?我当时以为应该阻止这种情况的发生。

解决方法

这是预期的结果。之所以happens是因为“如果尝试跳过文件终止符,则Get过程会传播异常End_Error。”在示例输入的上下文中,Get读取了3之后,End_Of_File仍然是FalseGet然后“跳过任何前导空白”,并在尝试读取“与数字文字的语法匹配的最长字符序列”时遇到文件结尾。

一种解决方案是捕获异常并按照用例的要求进行处理。例如,

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;

未生成异常。 一次读取输入文件一行,然后从上一行读取的字符串中读取以处理每个整数。 即使输入行包含结尾字符,此操作也不会例外。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...