0

我正在读取标准输入(一个文本文件并使用这样排列的数据进行计算:

 2 --This states the amount of following sets of info
 150 -- this is the first set of data
 250 -- this is the second set of data
 0 -- this is supposed to tell my program that this is the end of the two sets but
      keep looping because there might be multiple sets in here, seperated by "0"'s. 

我的 ADA 计划的基本大纲:

procedure test is

begin 

  while not end_of_file loop
  ......//my whole program executes


  end loop;
end test; 

我想知道如何告诉我的程序继续循环,直到没有什么可读的,但要记住零是分开数据集的,如果每个“0”之后有更多数据,则继续循环。

4

2 回答 2

3

我认为这个程序可以满足您的要求,无需过早退出循环:

with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Text_Io; use Ada.Text_Io;

procedure Reading_Data is
begin
   while not End_Of_File loop
      declare
         Number_Of_Sets : Natural;
      begin
         Get (Number_Of_Sets);
         if Number_Of_Sets > 0 then
            declare
               Sum : Integer := 0;
            begin
               for J in 1 .. Number_Of_Sets loop
                  declare
                     Tmp : Integer;
                  begin
                     Get (Tmp);
                     Sum := Sum + Tmp;
                  end;
               end loop;
               Put ("sum of");
               Put (Number_Of_Sets);
               Put (" elements is ");
               Put (Sum);
               New_Line;
            end;
         end if;
      end;
   end loop;
end Reading_Data;

但是,它不需要集合之间的0分隔符;0只是意味着“这是一个没有元素的集合,忽略它”。

现在,如果这是您需要检查数据一致性的问题的简化示例(即,如果您承诺 2 个元素,那么在读取 2 个元素之后,您要么位于文件末尾,要么存在 a 0),则此解决方案将不正确。(你可能会认为我已经过分使用declare块来最小化变量的范围......)

有输入:

1
10
0
2
20 30
3 40 50 60

程序给出输出:

sum of          1 elements is          10
sum of          2 elements is          50
sum of          3 elements is         150
于 2015-02-14T15:04:59.227 回答
1

使用标签编写循环:

Until_Loop :
   While not end_of_file loop

      X := X + 1;
      ......//my whole program executes;

      exit Until_Loop when X > 5;//change criteria to something 
                                 //relating to no more files 
                                 //(whatever that will be)
   end loop Until_Loop;  

编辑- 关于评论中嵌套循环的问题:

示例: 从这里

Named_Loop:
   for Height in TWO..FOUR loop
      for Width in THREE..5 loop
         if Height * Width = 12 then
            exit Named_Loop;
         end if;
         Put("Now we are in the nested loop and area is");
         Put(Height*Width, 5);
         New_Line;
      end loop;
   end loop Named_Loop;
于 2015-02-12T22:25:57.070 回答