2015-06-07 154 views
0

我试图在我的程序中输入一个单词,其中限制为16个字符。问题是我必须输入完整的16个字符才能继续执行程序中的下一步。我希望能够输入少于16个字符。这是代码的一部分。字符数组的最大长度

编辑:虽然我仍然有点困惑。我没有使用字符串;我正在使用填充字符的数组,并添加了SextonTecken_Type的声明。我做了一些改变,但我仍然有同样的问题。我无法输入一个较短的词来推进。

type SextonTecken_Type is 
    array (1..16) of Character; 

procedure Gett(A: out SextonTecken_Type; N: in Integer) is  
begin 
    Put("Type a string (max. 16 characters): "); 
    for I in 1..16 loop 
     Get(A(I)); 
     if N=16 then 
      Skip_Line; 
     end if; 
    end loop; 
end Gett; 

回答

4

Ada.Text_IO,使用Get_Line; Last参数将包含“Item(Last)是指定的最后一个字符的索引值。”

with Ada.Text_IO; 
… 
Line : String (1 .. 16); 
Last : Natural; 
… 
Ada.Text_IO.Get_Line (Line, Last); 
Ada.Text_IO.Put_Line (Line(1 .. Last)); 

附录:

我使用填充有字符的数组。

为了方便收集字符,我仍然使用Get_Line。与String类似,您的类型SextonTecken_TypeCharacter类型的元素的数组。您可以从一个数组中的元素复制到另一个:

type SextonTecken_Type is array (1..16) of Character; 
Buffer : SextonTecken_Type; 
… 
for I in 1 .. Last loop 
    Buffer(I) := Line(I); 
end loop; 

或者,让SextonTecken_TypeString一个subtype和使用assignment

subtype SextonTecken_Type is String (1 .. 16); 
Buffer : SextonTecken_Type; 
… 
Buffer(1 .. Last) := Line(1 .. Last); 
Ada.Text_IO.Put_Line(Buffer(1 .. Last)); 
+1

根据定义,'String' **是一个**字符数组;因此,只要'String'的长度为16(否则在运行时会得到一个'Constraint_Error'),而不是复制每个元素,我认为只需在'String'和'SextonTecken_Type'之间进行类型转换即可。 – ajb

+0

@ajb只要元素类型和索引类型的基数相同,就可以通过显式转换进行转换。 –

1

嗯,你可以改变的事情,像这样:

-- Normal subtype indexing; requires SextonTecken_Type to be incompatible w/ String. 
subtype Index_Range is Positive range 1..16; 
type SextonTecken_Type is array (Index_Range range <>) of Character; 

-- Ada 2012 style dynamic predicate; subtype compatible w/ String. 
subtype SextonTecken_Type is String 
with Dynamic_Predicate => SextonTecken_Type'Length <= 16; 

而且这将确保字符串SextonTecken_Type的长度为16或更小。