Ada:获取用户对String(1..10)的输入并用空格填充其余部分

use*_*914 8 string input ada

我已经定义了

subtype String10 is String(1..10);
Run Code Online (Sandbox Code Playgroud)

我试图获得键盘输入,而无需在输入之前手动输入空格.我尝试了get_line()但是由于某些原因它在输出get put()命令之前实际上不会等待输入,而且我也认为它会在那之前留下字符串中的内容并且不用空格填充它.

我知道并使用了Bounded_String和Unbounded_String,但我想知道是否有办法使这项工作.

我试过为它做一个函数:

--getString10--
procedure getString10(s : string10) is
   c : character;
   k : integer;
begin
   for i in integer range 1..10 loop
      get(c);
      if Ada.Text_IO.End_Of_Line = false then
         s(i) := c;
      else
         k := i;
         exit;
      end if;
   end loop;

   for i in integer range k..10 loop
      s(i) := ' ';
   end loop;
end getString10;
Run Code Online (Sandbox Code Playgroud)

但是,在这里,我知道这s(i)不起作用,我不认为

"if Ada.Text_IO.End_Of_Line = false then" 
Run Code Online (Sandbox Code Playgroud)

做我希望它会做什么.它只是一个占位符,而我正在寻找实际的方法.

我一直在搜索几个小时,但是Ada文档不像其他语言那样可用或清晰.我找到了很多关于获取字符串的内容,但不是我正在寻找的内容.

Kei*_*son 7

在调用之前,只需用空格预先初始化字符串Get_Line.

这是我刚刚聚集在一起的一个小程序:

with Ada.Text_IO; use Ada.Text_IO;
procedure Foo is
    S: String(1 .. 10) := (others => ' ');
    Last: Integer;
begin
    Put("Enter S: ");
    Get_Line(S, Last);
    Put_Line("S = """ & S & """");
    Put_Line("Last = " & Integer'Image(Last));
end Foo;
Run Code Online (Sandbox Code Playgroud)

以及运行时得到的输出:

Enter S: hello
S = "hello     "
Last =  5
Run Code Online (Sandbox Code Playgroud)

另一种可能性,而不是预先初始化字符串,是在调用后将余数设置为空格Get_Line:

with Ada.Text_IO; use Ada.Text_IO;
procedure Foo is
    S: String(1 .. 10);
    Last: Integer;
begin
    Put("Enter S: ");
    Get_Line(S, Last);
    S(Last+1 .. S'Last) := (others => ' ');
    Put_Line("S = """ & S & """");
    Put_Line("Last = " & Integer'Image(Last));
end Foo;
Run Code Online (Sandbox Code Playgroud)

对于非常大的数组,后一种方法可能更有效,因为它不会将字符串的初始部分分配两次,但实际上差异不太可能很大.

  • +1实际解决问题.:-) @ user1279914:另见[*4.3.3 Array Aggregates*](http://www.adaic.org/resources/add_content/standards/05rm/html/RM-4-3-3.html). (2认同)