如何从标准输入循环遍历多个数据集

时间:2015-02-12 22:18:42

标签: ada ada2012

我正在阅读标准输入(一个文本文件,并使用如下排列的数据进行计算:

 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; 

我想知道如何告诉我的程序继续循环,直到无需阅读,但要记住,ZERO分离数据集并在每个&#34后有更多数据时保持循环; 0&#34 ;.

2 个答案:

答案 0 :(得分: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个元素之后,你要么在文件的末尾,要么是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

答案 1 :(得分: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;  

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

示例: from here

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;