【问题标题】:Ada Reading a line of characters from a file and storing them in an arrayAda 从文件中读取一行字符并将它们存储在一个数组中
【发布时间】:2014-06-25 01:48:15
【问题描述】:

我想在我的数组中的指定索引处存储由空格分隔的每个字符块。这是我的代码:

with Ada.Text_IO; use Ada.Text_IO;

procedure Test_Read is

    Input_File    : File_Type;
    type Arr_Type is array (Integer range <>) of Character;
    Arr :   Arr_Type (1 .. 3);

begin

   Ada.Text_IO.Open (File => Input_File, Mode => Ada.Text_IO.In_File, Name => "input.txt");

    while not End_OF_File (Input_File) loop
        Ada.Text_IO.Get (File => Input_File, Item => Arr(1));
        Ada.Text_IO.Put (Item => Arr(1));
    end loop;

 Ada.Text_IO.Close (File => Input_File); 

end Test_Read;

文件“input.txt”包含:

ABCD EFGH IJK

我为 Put(Arr(1)) 得到的输出是整行:

ABCD EFGH IJK

Put(Arr(1)) 我想要的输出是:

ABCD

【问题讨论】:

    标签: arrays file-io io ada


    【解决方案1】:

    首先,您的数据类型与问题不符。

    Character 类型包含单个 (ISO-8859-1) 字符。您的问题描述听起来像是您希望能够将每个块存储为未指定数量的字符。 Ada.Strings.Unbounded.Unbounded_String 类型适合该用途。

    with Ada.Strings.Unbounded;
    ...
       type Block_Of_Characters is new Ada.Strings.Unbounded.Unbounded_String;
    

    您的问题描述没有明确说明您期望的字符块数,但现在我假设您总是期望恰好三个块(正如您的示例数据和源文本都表明的那样)。

       type Block_Collection is array (Positive range <>) of Block_Of_Characters;
       Blocks : Block_Collection (1 .. 3);
    

    打开数据文件看起来不错。

    读取循环应该有点不同:

       Buffer : Character;
    begin
       Open (File => Input_File,
             Mode => In_File,
             Name => "input.txt");
    
       for Index in Blocks'Range loop
          Read_A_Single_Block :
          loop
             exit when Index = Blocks'Last and End_Of_File (Input_File);
    
             Get (File => Input_File,
                  Item => Buffer);
    
             exit Read_A_Single_Block when Buffer = ' ';
    
             Append (Source   => Blocks (Index),
                     New_Item => Buffer);
          end loop Read_A_Single_Block;
       end loop;
    

    【讨论】:

      【解决方案2】:

      虽然我上次在 Ada 中编写任何程序已经 22 年了,但很明显,您不是在检查空间。
      从指向 1 的数组索引变量开始。
      您需要检查您使用 Ada.Text_IO.Get 获得的字符是否为空格。
      如果是空格,则在索引中加一并始终使用 Arr(index)。
      这样您就可以将字符流分成几个数组。
      另外,请务必检查您的索引是否超出范围。

      【讨论】:

        猜你喜欢
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 2012-11-27
        • 2014-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多