我的问题非常简单,我的输入看起来像这样......
0 0 0 1 1 1 -1 -1 -1 1
Run Code Online (Sandbox Code Playgroud)
我需要将这些值存储到数组中,但我无法弄明白.这就是我到目前为止......
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type arr is array(1..10) of Integer;
Data : arr;
begin
for I in 1..arr'Length loop
Data(I) := Integer'Value(Get_Line);
end loop;
end Main;
Run Code Online (Sandbox Code Playgroud)
我知道这是错的,很明显为什么这不起作用.我试图将多个值存储到一个整数中,我需要一种迭代输入或一次加载所有值的方法.你会怎么在阿达做这个?
您可以使用Get_Line将整行作为字符串,然后使用Ada.Integer_Text_IO来解析字符串:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Hello is
Line : String := Get_Line;
Value : Integer;
Last : Positive := 1;
begin
while Last < Line'Last loop
Get(Line(Last..Line'Last),Value,Last);
Put_Line(Value'Image); -- Save the value to an array here instead
Last := Last + 1; -- Needed to move to the next part of the string
end loop;
end Hello;
Run Code Online (Sandbox Code Playgroud)
之后,您可以将值加载到循环中的数组中,或者您喜欢.
示例输出:
$gnatmake -o hello *.adb
gcc -c hello.adb
gnatbind -x hello.ali
gnatlink hello.ali -o hello
$hello
0
0
0
1
1
1
-1
-1
-1
1
Run Code Online (Sandbox Code Playgroud)
编辑:添加更一般的递归选项.这将从STDIN读取一行并递归地将值连接到一个数组中.它使用辅助堆栈在GNAT中执行此操作.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_Io;
procedure Hello is
-- Need an array return type
type Integer_Array is array (Positive range <>) of Integer;
-- Recursive function
function Get_Ints return Integer_Array is
Value : Integer;
begin
-- Read from STDIN using Integer_Text_IO;
Get(Value);
-- Concatinate recursively
return Integer_Array'(1 => Value) & Get_Ints;
exception
-- I found different exceptions with different versions
-- of GNAT, so using "others" to cover all versions
when others =>
-- Using Ada2012 syntax here. If not using Ada2012
-- then just declare the Empty variable somewhere
-- and then return it here
return Empty : Integer_Array(1..0);
end Get_Ints;
Result : Integer_Array := Get_Ints;
begin
Put_Line("Hello, world!");
Put_Line(Integer'Image(Result'Length));
for E of Result loop
Put(Integer'Image(E) & " ");
end loop;
end Hello;
Run Code Online (Sandbox Code Playgroud)